Shop_basicモデルと1対1関係にあるShopモデルが投稿したPostモデルを、Userモデルはお気に入りに登録できる、という機能を実装しています。
そこで、実際にお気に入りに登録する機能自体は実装できたのですが、
Viewにてデータを取得して表示させる際に、
post.shop.shop_basic.id
を取得しようとすると
【undefined method `shop_basic' for ...】
とエラーが出てしまいます。
以下のような関係を持つ複数のモデルを用いています。
問題のViewは以下のものです。
Ruby
1#app/views/users/favorite.html.erb 2<% @feed_posts.each do |pt| %> 3 4 <p><%= pt.post_title %></p> 5 <p><%= pt.shop.shop_basic.id %></p> 6 7<% end %>
Usersコントローラーのfavoriteは以下の様なものです。
Ruby
1 def favorite 2 @feed_posts = current_applicant.favorite_posts 3 end
モデルは以下のように記述しています。
Ruby
1 2class Shop < ActiveRecord::Base 3 has_one :shop_basic, dependent: :destroy, foreign_key: 'id',autosave: true 4 has_one :post, dependent: :destroy, foreign_key: 'id',autosave: true 5end 6 7class Post < ActiveRecord::Base 8 belongs_to :shop, foreign_key: "id", autosave: true 9 has_many :favorites 10 has_many :favorite_users, through: :favorites, source: :user 11end 12 13class User < ActiveRecord::Base 14 has_many :favorites 15 has_many :favorite_posts, through: :favorites, source: :post 16end 17 18class Fav < ActiveRecord::Base 19 belongs_to :user 20 belongs_to :post 21end
Viewで、
<%= pt.post_title %>
はうまく取得できているようなのですが、なぜこの場合、Postと関係を持つShopの情報が取得できないのでしょうか。
FavoriteとShopにリレーションが直接無いためかと思い、それぞれにhas_manyやbelongs_toなどいろいろ試してはみたのですが、うまくいきません。
どうすればこのリレーションでshopのデータを取得できるでしょうか。
ご教示よろしくお願いいたします。
情報追加
ShopBasicのモデルになります。
Ruby
1class SalonBasic < ActiveRecord::Base 2 belongs_to :shop, autosave: true, foreign_key: 'id' 3 4 before_create do 5 self.id = shop.id 6 end 7 8end
Ruby
1# == Schema Information 2# 3# Table name: shops 4# 5# id :integer not null, primary key 6# email :string default(""), not null 7# encrypted_password :string default(""), not null 8# number_of_post :integer default(1), not null 9# reset_password_token :string 10# reset_password_sent_at :datetime 11# remember_created_at :datetime 12# sign_in_count :integer default(0), not null 13# current_sign_in_at :datetime 14# last_sign_in_at :datetime 15# current_sign_in_ip :inet 16# last_sign_in_ip :inet 17# created_at :datetime not null 18# updated_at :datetime not null 19# 20# Indexes 21# 22# index_salons_on_email (email) UNIQUE 23# index_salons_on_reset_password_token (reset_password_token) UNIQUE 24#
Ruby
1# == Schema Information 2# 3# Table name: shop_basics 4# 5# id :integer not null, primary key 6# shop_name :string default(""), not null 7# shop_hp_address :string 8# representive_name :string 9# contact_personnel_name :string 10# farm_name :string 11# postal_code :string 12# farm_prefectures :string 13# farm_address :string 14# use_email :string default(""), not null 15# phone_number :string 16# contact_personnel_phone :string 17# created_at :datetime not null 18# updated_at :datetime not null 19#
他のページのViewではshop_basicの値もうまく取得できているので、以下のfavoriteアクションが悪さをしているのかなと思ってはいるのですが…
favorite_postsとsalonがリレーションを持てていないみたいです。
Ruby
1 def favorite 2 @feed_posts = current_applicant.favorite_posts 3 end
回答1件
あなたの回答
tips
プレビュー