具有可选字段的模型不保存

时间:2013-11-07 03:15:54

标签: ruby-on-rails ruby-on-rails-4 mongoid optional-parameters

在我的模型中,我有以下字段:

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 %>

字段“author”和“content”是必需的,其他字段是自动填充的(但正在工作)。问题是,当用户未填写“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

评论未能保存,但未设置“警报”,也未设置“通知”。它似乎只是崩溃并跳过整个方法。如果每个字段都填满,我只能保存评论,否则它会在没有任何消息的情况下失败。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

首先想到的是,由于某种原因,您要保留两次评论。首先,使用@article.comments.create(comment_params)代替@article.comments.new(comment_params)时保存。所以第一次保存失败,没有闪光灯。

我还建议您应用一些测试来查看哪些不起作用,或至少使用debugger gem来深入了解代码的实际内容。

相关问题