開発環境
rails 6.1.6
cloud9
やりたいこと
コメント機能の実装
現状
投稿一覧から投稿詳細ページに遷移しようとすると以下のエラーが出ます。
エラー周りのコード
post/show
1 <div class="comment-form"> 2 <%= form_with model: [@post, @comment], url: user_post_comments_path, local: true, method: :post do |f| %> 3 <%= f.text_area :comment_content, placeholder: "コメント記入欄" %><br/> 4 <%= f.submit "コメント" %> 5 <% end %> 6 </div>
post/controller
1class PostsController < ApplicationController 2 def new 3 @post = Post.new 4 @categories = Category.all 5 end 6 7 def create 8 @post = Post.new(post_params) 9 @post.user_id = current_user.id 10 if @post.save 11 end 12 redirect_to user_posts_path 13 end 14 15 def edit 16 @post = Post.find(params[:id]) 17 @categories = Category.all 18 end 19 20 def index 21 @posts = Post.all 22 end 23 24 def show 25 @post = Post.find(params[:id]) 26 @user = @post.user 27 @comment = Comment.new 28 end 29 30 def destroy 31 @post = Post.find(params[:id]) 32 @post.destroy 33 redirect_to user_posts_path 34 end 35 36 def update 37 @post = Post.find(params[:id]) 38 end 39 40 def search 41 @posts = Post.joins(:post_categories).where('post_categories.category_id = ?', params[:name]) 42 render :index 43 end 44 45 private 46 def post_params 47 params.require(:post).permit(:place_name, :body, :latitude, :longitude, :image, :name, category_ids: []) 48 end 49 50end
comments/controller
1class CommentsController < ApplicationController 2 3 4 def create 5 @post = Post.find(params[:id]) 6 comment = current_user.comments.new(comment_params) 7 comment.post_id = post.id 8 comment.save 9 redirect_to post_path(post) 10 end 11 12 def destroy 13 14 end 15 16 private 17 18 def comment_params 19 params.require(:comment).permit(:comment_contents) 20 end 21end 22
routes.rb
1 resources :users, except: [:new, :destroy] do 2 resources :posts do 3 resources :comments, only: [:create, :destroy] 4 end 5 end
詳細について
中間テーブルとしてcommentsテーブルがあります。
ネストさせているため、form_withでモデルを複数指定しており、URL指定していなければNoMethodError in Posts#show undefined method `post_comments_path' forと別のエラーが起きます。
原因が分かる方いらっしゃいましたら、ご教授いただければ幸いです。

回答3件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
また依頼した内容が修正された場合は、修正依頼を取り消すようにしましょう。