Railsで多対多のアソシエーションの実装をしています。
中間テーブルを経由してタグとユーザーを関連づけて、「ユーザーはたくさんのタグをもつ、タグはたくさんのユーザーをもつ」
という機能を実装しようとしています。
発生している問題・エラーメッセージ
ActiveRecord::RecordNotFound (Couldn't find Tag with 'id'=): app/controllers/tags_controller.rb:4:in `show'
該当のソースコード
tags_controller.rb
1class TagsController < ApplicationController 2 def show 3 @tag = Tag.find(params[:tag_id]) 4 end 5end 6
@tag = Tag.find(params[:tag_id])
こちらがエラーとなっていいる文法です。
以下3つのモデルがありますが、ここは関係していないように思いました。
class User < ApplicationRecord has_many :user_tag_relations, dependent: :destroy has_many :tags, :through =>:user_tag_relations end
class Tag < ApplicationRecord has_many :user_tag_relations, dependent: :destroy has_many :users, :through =>:user_tag_relations accepts_nested_attributes_for :user_tag_relations, allow_destroy: true end
class UserTagRelation < ApplicationRecord belongs_to :user belongs_to :tag end
tableもみてみたのですが、、、
class CreateUsers < ActiveRecord::Migration[5.1] def change create_table :users do |t| t.string :name t.timestamps end end end
class CreateTags < ActiveRecord::Migration[5.1] def change create_table :tags do |t| t.string :name t.timestamps end end end
class CreateUserTagRelations < ActiveRecord::Migration[5.1] def change create_table :user_tag_relations do |t| t.references :user, foreign_key: true t.references :tag, foreign_key: true t.timestamps end end end
最終的にはこちらでtagに基づいたuserのnameを表示したいです。
<% @tag.tag_users_relations.each do |tag_user|%> <%=tag_user.user.name%> <%end%>
試したこと
ここに問題に対して試したことを記載してください。
find_byをしようしてみたり、参考サイトをみてidを振ったりしましたが、k解決できなかったので質問させていただきました。
ご教授お願いしたいです????♀️
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/05/29 06:21
2019/05/29 06:24