我在评论框之前创建了一个添加评论的表单。遗憾的是,似乎这个表单在集合中创建了一个空对象,该对象在没有内容的注释中显示。我该如何防止这种情况?
.comments
= simple_form_for [@post, @post.comments.build] do |f|
= f.input :content, label: "Comment"
= f.button :submit
- @post.comments.each do |c|
p = c.content
p = c.user.profile.full_name unless c.user.nil? || c.user.profile.nil?
# comments_controller.rb
class CommentsController < ApplicationController
before_action :find_commentable
def index
@commentable = find_commentable
@comments = @commentable.comments
end
def create
@commentable = find_commentable
@comment = @commentable.comments.build(comment_params)
@comment.user = current_user
if @comment.save
flash[:notice] = "Successfully created comment."
redirect_to @commentable
else
redirect_to @commentable
end
end
private
def comment_params
params.require(:comment).permit(:content)
end
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
end
答案 0 :(得分:0)
您可以做的是不显示非持久性记录。你可以这样做:
- @post.comments.each do |c|
- next unless c.persisted?
...
或:
- @post.comments.find_all(&:persisted?).each do |c|
...