実現したいこと
・コメント機能の実装
前提
・ruby on railsでユーザー認証機能を行い、画像投稿ができ、投稿に対してコメント・いいねできるwebサイトを作成しています。
・現在、ログイン後、投稿に対してコメント実装中。
・サイト上でのエラーメッセージは出ていません。
質問内容の詳細
・コメント投稿フォームから投稿すると、詳細ページに戻りますが、データを受け取れていないのかコメントのカウントは0のままです。
・初心者でデータの行き来を理解していない部分があります。
・拙い文章で失礼します。
/config/routes.rb Rails.application.routes.draw do devise_for :users root to: "homes#top" get "/homes/about" => "homes#about", as: "about" resources :post_images, only: [:new, :create, :index, :show, :destroy] do resources :post_comments, only: [:create, :destroy] end resources :users, only: [:show, :edit, :update] # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
/app/controllers/post_comments_controller.rb class PostCommentsController < ApplicationController def create post_image = PostImage.find(params[:post_image_id]) comment = current_user.post_comments.new(post_comment_params) comment.post_image_id = post_image.id comment.save redirect_to post_image_path(post_image) end def destroy PostComment.find(params[:id]).destroy redirect_to post_image_path(params[:post_image_id]) end private def post_comment_params params.require(:post_comment).permit(:comment) end end
/app/views/post_images/show.html.erb <div> <%= image_tag @post_image.get_image %> <p>ショップ名:<%= @post_image.shop_name %></p> <p>説明:<%= @post_image.caption %></p> <p>投稿ユーザー画像:<%= image_tag @post_image.user.get_profile_image(100,100) %></p> <p>ユーザーネーム:<%= @post_image.user.name %></p> <p>投稿日:<%= @post_image.created_at.strftime('%Y/%m/%d') %></p> <% if @post_image.user == current_user %> <%= link_to "削除", post_image_path(@post_image), method: :delete %> <% end %> </div> <div> <p>コメント件数:<%= @post_image.post_comments.count %></p> <% @post_image.post_comments.each do |post_comment| %> <p><%= image_tag post_comment.user.get_profile_image(100,100) %></p> <%= post_comment.user.name %> <%= post_comment.created_at.strftime('%Y/%m/%d') %><%= post_comment.comment %> <% if post_comment.user == current_user %> <%= link_to "削除", post_image_post_comment_path(post_comment.post_image, post_comment), method: :delete %> <% end %> <% end %> </div> <div> <%= form_with model: [@post_image, @post_comment] do |f| %> <%= f.text_area :comment, rows: '5', placeholder: "コメントをここに" %> <%= f.submit "送信する" %> <% end %> </div>
試したこと
・contorller.rbでsave!メソッドを追加したところ、下記のエラーメッセージが出ました。
補足情報(FW/ツールのバージョンなど)
・Rails version 6.1.7
よろしくお願いいたします。
回答2件
あなたの回答
tips
プレビュー