【发布时间】:2013-11-07 03:15:53
【问题描述】:
在我的模型中,我有以下字段:
class Comment
include Mongoid::Document
field :author, type: String
field :author_email, type: String
field :author_url, type: String
field :author_ip, type: String
field :content, type: String
validates :author, presence: true, length: { minimum: 4 }
validates :content, presence: true, length: { minimum: 8 }
end
我还有一个表单,用于提交“评论者”可能提供的字段:
<%= form_for [@article, @article.comments.build] do |f| %>
<div class='comment_content'>
<%= f.text_area :content %>
</div>
<div class='comment_author_email'>
<%= f.email_field :author_email %>
</div>
<div class='comment_author'>
<%= f.text_field :author %>
</div>
<div class='comment_author_url'>
<%= f.url_field :author_url %>
</div>
<div class='comment_submit'>
<%= f.submit %>
</div>
<% end %>
“作者”和“内容”字段是必需的,其他字段是自动填写的(但正在工作)。问题是,当用户没有填写可选的“URL”字段时,模型不会保存评论。跟随我的控制器:
class CommentsController < ApplicationController
def create
@article = Article.find params[:article_id]
@comment = @article.comments.create(comment_params)
@comment.author_ip = request.remote_ip
if @comment.save
flash[:notice] = 'Comment published'
else
flash[:alert] = 'Comment not published'
end
redirect_to article_path(@article)
end
private
def comment_params
params.require(:comment).permit(:content, :author_email, :author, :author_url)
end
end
评论保存失败,但没有设置“警告”,也没有设置“通知”。似乎它只是崩溃并跳过了整个方法。如果每个字段都填写,我只能保存评论,否则它将失败而没有任何消息。
我错过了什么?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 mongoid optional-parameters