【问题标题】:Error messages of nested attributes's required field are not displayed不显示嵌套属性必填字段的错误消息
【发布时间】:2016-03-17 16:02:08
【问题描述】:

就我而言,我的客户有很多任务(需要 :detail 和 :completion_date 字段。)。 我一直在构建一个嵌套模型表单,如下所示:

= simple_form_for @client do |f|
  = f.simple_fields_for :tasks do |task|
    = task.input :detail
    = task.input :completion_date
  = f.submit

当提交的表单没有空的“详细信息”或“完成日期”字段时,表单会重新呈现,但不会显示任何错误消息。

我整天都在努力寻找解决方案。这些都没有提到嵌套对象的属性验证失败。

希望任何人都可以提供帮助! 谢谢,

【问题讨论】:

  • 您是否在您的client 模型中添加了accepts_nested_attributes_for :tasks?为此,您还需要允许参数。
  • 感谢@chinloong 的快速回复。实际上,我已经添加了这些。我只是没有包括在我的问题中。对此感到抱歉。

标签: ruby-on-rails nested-forms nested-attributes simple-form-for


【解决方案1】:

Rails 默认不验证关联对象。您需要使用validates_associated macro

例子:

class Client < ActiveRecord::Base
  has_many :tasks
  accepts_nested_attributes_for :tasks
  # Do not add this on both sides of the association
  # as it will cause infinate recursion.
  validates_associated :tasks
end

class Task < ActiveRecord::Base
  belongs_to :client
  validates_presence_of :name
end

@client = Client.create(tasks_attributes: [ name: "" ])
@client.errors.messages
=> {:"tasks.name"=>["can't be blank"], :tasks=>["is invalid"]}

关联记录的错误未在父项中汇总。要显示子记录的错误,您需要遍历它们并调用 errors.full_messages。

@client.tasks.each do |t|
  puts t.errors.full_messages.inspect
end

【讨论】:

  • 感谢@max 的快速回复。实际上,我的 Client 和 Task 模型已经像您在此处显示的那样编写,但我只是没有将其包含在我的问题中。为此事道歉。另外,我还可以检查错误消息。我的问题是错误消息没有直接显示在每个输入字段的视图中(例如输入框周围的红色边框和下方的红色错误文本)。
  • 您最终找到解决方案了吗?卡在同一件事上
  • 关联记录的错误未在父项中聚合。要显示子记录的错误,您需要遍历它们并调用errors.full_messages
猜你喜欢
  • 1970-01-01
  • 2012-08-19
  • 2011-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多