【问题标题】:Model with optional fields not saving具有可选字段的模型未保存
【发布时间】: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


    【解决方案1】:

    首先想到的是您出于某种原因保存了两次评论。首先,在使用@article.comments.create(comment_params) 而不是@article.comments.new(comment_params) 时保存它。所以第一次保存失败,没有 flash。

    我还建议您应用一些测试来看看有什么问题,或者至少使用debugger gem 来窥探正在运行的代码。

    【讨论】:

    • 这解决了部分问题。它仍然保存为"",但我修复了这个:before_create { self.unset(:author_url) if self.author_url.empty? }
    • 我推荐使用 .blank?对于那个过滤器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2020-11-15
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多