現在facebookのようなアプリをrailsで作成しようとしています。
イメージとしてはこのように、データベースで関連付ければ良いのかと考えました。
https://gyazo.com/735ed14dd8fbf57b6588396771dc5f61
コメントの1つ目のuser_idは誰の記事かを特定するためのもの、
2つ目のuser_idは誰がコメントしたかを特定するためのものです。
そこで、
会員は複数の記事を持ち、
各ユーザーは、複数の記事に対してコメントをすることができます。
その際に、
記事にはユーザーの外部キー(user_id)を class CreateMicroposts < ActiveRecord::Migration def change create_table :microposts do |t| t.string :content t.references :user, index: true t.timestamps null: false t.index [:user_id, :created_at ] end end end コメントにはユーザー(user_id)と記事(micropost_id)の外部キーを class CreateComments < ActiveRecord::Migration def change create_table :comments do |t| t.references :user, index: true t.references :micropost, index: true t.string :content t.timestamps null: false t.index [:user_id,:micropost_id ,:created_at ] end end end
を持っています。
それらを利用して、
どのユーザーのなんという記事にコメントをしたのかわかるように、
したいのですが、
ユーザーコントローラーで
def show @user = User.find(params[:id]) @microposts = @user.microposts @comment = @microposts.comments.build @comments = @microposts.comments end
と記述し、
コメントコントローラ内で、
def create @comment = current_user.microposts.comments.build(comment_params) if @comment.save flash[:success] = "コメントしました。" redirect_to root_path else render 'static_pages/home' end end
と記述し、起動してみますと、
NoMethodError (undefined method `comments' for #<Micropost::ActiveRecord_Associations_CollectionProxy:0x007f3c1e1ac8e8>):
とエラーが発生してしまいます。
ですが、
ユーザーコントローラー内で
@user = User.find(params[:id]) @microposts = @user.microposts @comment = @user.comments.build @comments = @user.comments
コメントコントローラー内で
@comment = current_user.comments.build(comment_params)
と記述しすると
ユーザーidだけ上手く紐づいて作成することに成功しました。
コントローラー内で、
どのように、記述を行えば、
ユーザーと記事に紐づいたコメントを作成することができるのでしょうか??
お手数お掛けしますが、
アドバイスよろしくお願いします。
これが、
ユーザーモデルです。
class User < ActiveRecord::Base has_one :member has_many :microposts has_many :comments has_secure_password accepts_nested_attributes_for :member end
記事のモデルはこうです。
class Micropost < ActiveRecord::Base belongs_to :user has_many :comments end
コメントモデルではこうです。
class Comment < ActiveRecord::Base belongs_to :micropost belongs_to :user end
現在はこのような関連を作成しています。
回答1件