前提・実現したいこと
Postにcomment機能を作っています。
作成された1つのcommentを編集する時に他のcommentの内容も更新されてしまいます。
原因はcommentを取得出来ていないことでcomment controllerに問題があると思うのですが、Routingがネストされているのもありcommentの取得の考え方がわからないです。
comment毎に編集&更新できるようにしたいです。
該当のソースコード
ruby
1 2 class CommentsController < ApplicationController 3 4 def edit 5 6 @post = Post.find(params[:post_id]) 7 @comment = @post.comments.find(params[:id]) 8 end 9 10 def update 11 @post = Post.find(params[:post_id]) 12 @comment = @post.comments.update(comment_params) 13 redirect_to post_path(@post) 14 end 15 16private 17 def comment_params 18 params.require(:comment).permit(:content) 19 end 20 21end 22
edit
1<%= form_for [@post, @comment] do |f| %> 2 <p> 3 コメント: <%= f.text_area :content, cols: 40, rows: 3 %> 4 </p> 5 <div><%= f.submit %>Update</div> 6<% end %> 7
routes
1 2Rails.application.routes.draw do 3 root 'home#index' 4 resource :home 5 resources :posts do 6 resources :comments 7 end 8 9end 10
試したこと
def update @post = Post.find(params[:post_id]) #2 @comment = @post.comments.find(params[:id]) @comment = @post.comments.update(comment_params) redirect_to post_path(@post) end
CommentsControllerでPostのidを取得した後に#2を加えてcommentのidを取得してから更新することで個別のcommentの情報を取得できることを期待したが、挙動は変わらなかったです。。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。