現在Facebookのような機能をRailsで作成しています。
ユーザは複数の記事と複数のコメントを持ち、
複数の記事は一人のユーザに帰属し、コメントも1つの記事に帰属するという関係です。
ユーザモデル 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
現在、ユーザコントローラとコメントコントローラをこのように記述することで、
ユーザと記事に紐付いたコメントを作成することに成功しました。
*current_userはログイン中のユーザを表しています。
ユーザコントローラ class UsersController < ApplicationController def show @user = User.find(params[:id]) @micropost = Micropost.find(params[:id]) @microposts = @user.microposts @microposts.each do |micropost| @comment= micropost.comments.build @comment.user = current_user end end end コメントコントローラ class CommentsController < ApplicationController def create @microposts = current_user.microposts @comment = Comment.new(comment_params) @microposts.each do |micropost| @comment.micropost = micropost end @comment.user = current_user if @comment.save flash[:success] = "コメントしました。" redirect_to root_path else render 'static_pages/home' end end end
ですが、
どの記事にコメントしても、
最後の記事に紐付いたコメントを作成してしまいます。
INSERT INTO "comments" ("content", "micropost_id", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["content", "s"], ["micropost_id", 3], ["user_id", 1], ["created_at", "2016-01-05 08:14:59.920023"], ["updated_at", "2016-01-05 08:14:59.920023"]]
これを、
ユーザの記事1に対しては、
INSERT INTO "comments" ("content", "micropost_id", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["content", "s"], ["micropost_id", 1], ["user_id", 1], ["created_at", "2016-01-05 08:14:59.920023"], ["updated_at", "2016-01-05 08:14:59.920023"]]
ユーザの記事2に対しては
INSERT INTO "comments" ("content", "micropost_id", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["content", "s"], ["micropost_id", 2], ["user_id", 1], ["created_at", "2016-01-05 08:14:59.920023"], ["updated_at", "2016-01-05 08:14:59.920023"]]
のように個々の記事に紐付いたコメントを作成するためには、
どう修正すればよいのでしょうか?
お手数おかけしますが、
アドバイス宜しくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/01/06 09:17
2016/01/06 22:24
2016/01/07 09:28