以下のようなリレーションの時に、あるブログに紐づくタグの一覧
を表示させるにはどうすればよいでしょうか?
lang
1# blogモデル 2class Blog < ActiveRecord::Base 3 has_many :articles 4 has_many :blog_tag_relations 5 has_many :tags, through: :blog_tag_relations 6end 7 8# tagモデル 9class Tag < ActiveRecord::Base 10 has_many :blog_tag_relations 11 has_many :blogs, through: :blog_tag_relations 12end 13 14# blogとtagの中間テーブル 15class BlogTagRelation < ActiveRecord::Base 16 belongs_to :blogs 17 belongs_to :tags 18end
BlogController
lang
1 def show 2 @blog = Blog.find(params[:id]) 3 @articles = @blog.articles 4 @tags = @blog.tags # NameError in BlogsController#show 5 end
ちなみに中間テーブルのモデルで以下のように単数形にしたところ、エラーは出なくなりましたが、Tag
としか一覧に表示されませんでした。
lang
1# blogとtagの中間テーブル 2class BlogTagRelation < ActiveRecord::Base 3 belongs_to :blog # 単数形にした 4 belongs_to :tag # 単数形にした 5end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。