我正在尝试使用 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
这是我的comment_controller.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>
这个_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
有什么帮助吗?
答案 0 :(得分: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