Ruby on rails:如何在不刷新页面的情况下发布评论


  • 我正试图使用rails 6和jQuery实现评论功能,但我希望用户可以在不刷新浏览器的情况下向帖子添加评论,我创建了一个comment_controller.rb和模型comment.rb,

  • 然后我通过has_many:comments将帖子、用户和评论模型关联起来,并属于用户和帖子,但问题是当我试图创建帖子时,我发现了这个错误:

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
  • 这是我的评论控制器.rb

    class CommentsController < ApplicationController
    before_action :authenticate_user!
    def create  
    @comment = Comment.new(comment_params)
    @comment.user_id = current_user.id if user_signed_in?
    @comment.save           
    end
    def destroy 
    @comment.destroy  
    end
    private
    def comment_params
    params.require(:comment).permit(:body, :user_id, :post_id)
    end
    end
    
  • 这是我的index.html.erb中的评论行:

    <div id="comment_pane" class=" comment-box " >
    <%= render "comments/comments", post: post %>
    </div>
    <div class="bottom border-t pt-3 mt-3">
    <%= render  'comments/form' %>
    </div>
    
  • this _form.html.erb:

    <%= form_for Comment.new, remote: true  do |f| %>
    <%= f.hidden_field :user_id, value: current_user.id %>
    <%= f.text_field :body, placeholder: "add comment here ..." %>
    <%= f.submit "Post", class: "comment-button text-blue-500 opacity-75 w-2/12 text-center font-bold", autocomplete: :off %>
    <% end %>
    
  • create.js.erb:

    $('#comment_pane').append("<%= j render @post.comments.last %>");
    $('#comment_body').val('');
    
  • 我面临的问题是,在用户提交评论后,我发现了这个错误:

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

请帮忙吗?

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

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

最新更新