作成中のアプリケーション
ライブ情報を一覧表示できるアプリケーションを作成中です。
ユーザー新規登録をウィザード形式で、 ライブハウスの画像(active_storageで実装)、住所等を
mysqlに保存することができました。
ユーザー: admin_usersテーブル
住所、プロフィール等: admin_profilesテーブル
アソシエーション
admin_user has_one admin_profile
admin_profile belongs_to admin_user
解決したいこと
admin_userのshowアクションのビューであるshow.html.erbに
admin_profileの住所やライブハウスの画像(actice_strage)の情報を表示したいです。
admin_users_controllerに
class AdminUsersController < ApplicationController def show admin_user = AdminUser.find(params[:id]) @store_name = admin_user.store_name @admin_profile = admin_user.admin_profile end end
と記述し表示を試みましたが
NoMethodErrorとなりました。
また、コントローラーの
@admin_profileの前の行にbinding.pryを記述し、
@admin_profileとターミナルに入力すると
nilが帰ってきました。
どなたかcontrollerでどのように定義すると
has_one型のテーブルから値を取得することができるのか
お教え頂けないでしょうか?
追記
admin_users/show.html.erb
<p class="postal-code"> 〒 <%= @admin_profile.postal_code %> </p> <p class="prefecture-text"> <%= "都道府県" %><%= "市区町村" %>
上記の@admin_profile.postal_codeの箇所で
NoMethodError, undefined method `postal_code' for nil:NilClass
となっております。
モデルの関連付け
AdminUserモデル
class AdminUser < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable PASSWORD_REGGEX = /\A(?=.*?[a-z])(?=.*?\d)[a-z\d]+\z/i.freeze validates_format_of :password, with: PASSWORD_REGGEX validates :store_name, presence: true has_many :events has_one :admin_profile end
AdminProfileモデル
class AdminProfile < ApplicationRecord belongs_to :admin_user, optional: true has_one_attached :admin_image extend ActiveHash::Associations::ActiveRecordExtensions belongs_to :prefecture with_options presence: true do validates :postal_code, format: { with: /\A[0-9]{3}-[0-9]{4}\z/ } validates :prefecture_id, numericality: { other_than: 1, message: "can't be blank" } validates :municipality validates :address validates :phone_number, format: { with: /\A\d{10,11}\z/ } validates :profile validates :admin_image end end
試したこと
ターミナルで
[1] pry(main)> AdminUser.pluck(:id) (0.3ms) SELECT `admin_users`.`id` FROM `admin_users` => [5, 16, 7, 14, 12, 15, 6, 8, 13, 1, 11, 9, 4, 18, 3, 17, 2, 10] [2] pry(main)> AdminProfile.pluck(:admin_user_id) (0.3ms) SELECT `admin_profiles`.`admin_user_id` FROM `admin_profiles` => [4, 6, 7, 13, 14, 15, 17, 18]
が確認できました。
回答1件
あなたの回答
tips
プレビュー