Ruby rails:如何在不刷新页面的情况下 post 发表评论?

Ruby on rails: how to post a comment without refreshing the page?

app/controllers/comments_controller.rb:8:in `create'
Started POST "/comments" for ::1 at 2021-06-10 09:56:42 +0200
Processing by CommentsController#create as JS
  Parameters: {"comment"=>{"user_id"=>"1", "body"=>"good one ;)"}, "commit"=>"Post"}
   (3.8ms)  SELECT sqlite_version(*)
  User Load (15.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
  TRANSACTION (0.1ms)  begin transaction
  ↳ app/controllers/comments_controller.rb:11:in `create'
  User Load (0.5ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/comments_controller.rb:11:in `create'
  TRANSACTION (0.1ms)  rollback transaction
  ↳ app/controllers/comments_controller.rb:11:in `create'
  Rendering comments/create.js.erb
  Rendered comments/create.js.erb (Duration: 294.2ms | Allocations: 1386)
Completed 500 Internal Server Error in 7130ms (ActiveRecord: 105.2ms | Allocations: 21119)

ActionView::Template::Error (undefined method `comments' for nil:NilClass):
    1:
    2: $('#comment_pane').append("<%= j render @post.comments.last %>");
    3: $('#comment_body').val('');

app/views/comments/create.js.erb:2
undefined method `comments' for nil:NilClass  
app/views/comments/create.js.erb:2

有什么帮助吗?

您收到错误是因为您的视图期望 @post 存在但未定义。您可以修改 CommentsController#create 以包含创建的评论的 post.

class CommentsController < ApplicationController
    def create  
        @comment = Comment.new(comment_params)
        @comment.user_id = current_user.id if user_signed_in?
        @comment.save
        @post = @comment.post # or Post.find(comment_params[:post_id])
    end
end