ruby 3.1.0, rails 7.0.2.2の環境下でsnsの様なアプリを開発中です。
userが投稿したmicropostにcomment機能をつける際に以下の様なエラーメッセージが出現しました。
以下関係していると思われるcodeです
routes.rb
1 resources :microposts do 2 resources :comments, only:[:create] 3 end
migrate/create_comments.rb
1class CreateComments < ActiveRecord::Migration[7.0] 2 def change 3 create_table :comments do |t| 4 t.string :comment 5 t.references :user, null: false, foreign_key: true 6 t.references :micropost, null: false, foreign_key: true 7 8 t.timestamps 9 end 10 end 11end 12
user.rb
1 has_many :comments, foreign_key: "user_id", dependent: :destroy
micropost.rb
1 has_many :comments, foreign_key: "micropost_id"
comment.rb
1 belongs_to :user 2 belongs_to :micropost
microposts_controller.rb
1 def show 2 @user = current_user 3 @micropost = Micropost.find_by(id: params[:id]) 4 @comments = @micropost.comments 5 @comment = @micropost.comments.new 6 end
comments_controller.rb
1 def create 2 @comment = current_user.comments.new(comment_params) 3 4 respond_to do |format| 5 if @comment.save 6 format.html { redirect_to root_path} 7 else 8 format.html { render root_path, status: :unprocessable_entity} 9 format.json {render json: @comment.errors, status: :unprocessable_entity } 10 end 11 end 12 end 13 14 private 15 def comment_params 16 params.require(:comment).permit(:comment_content, :post_id) #formにてpost_idパラメータを送信して、コメントへpost_idを格納するようにする必要がある。 17 end
_micropost.html.erb
1<% if controller_name == "microposts" && action_name == "show"%> 2 <% @comments.each do |c| %> 3 <%= c.comment%> 4 <% end %> 5 6 <%= form_with(model: @comment, local: true) do |form| %> 7 <%= form.text_field :comment, class: "block bg-red-50"%> 8 <%= form.submit "add comment" %> 9 <% end %> 10<% end %>
micropostのparcialはindexなどでも使っているのでif文でコメントが表示される条件を指定しています。
@commentに正しい値が入っていないことが原因かと思うのですが、具体的に何がいけないのかがわかりません。
アプリの仕様としましては、全てのユーザーが全ての投稿にコメントした人の情報とともにコメントできる様にしたいです。
よろしくお願いします
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。