【问题标题】:Validation on formtastic nested fields对表单嵌套字段的验证
【发布时间】:2016-11-09 23:20:02
【问题描述】:

我的代码中有一个一对多关联,如下所示:

class Second < ActiveRecord::Base
    has_many :firsts
end
class First < ActiveRecord::Base
    belongs_to :second
    accepts_nested_attributes_for :second
end

在我的 erb 中,我有:

<%= f.input :one_field, :label => false %>
<%= f.semantic_fields_for :second do |cp_f| %>
    <%= cp_f.input :another_field, :as => :string, :label => "another field" %>
<%= end %>

表单正确填充嵌套表中的数据。

我需要在控制器中进行一些验证,并且我想将用户指向发生错误的字段。如果我写这样的错误:

errors.add :one_field, "This is wrong"

这没有问题,并将错误放在字段旁边的页面上。但我想对嵌套字段做同样的事情,比如:

errors.add :second.another_field, "Another wrong one"

但我得到一个错误:

undefined method `another_field' for :second:Symbol

有没有办法在嵌套字段上放置错误?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 formtastic


    【解决方案1】:

    问题在于访问 First 的 errors 成员。我需要的是:

    second.errors.add :another_field, "Another wrong one"
    

    【讨论】:

      猜你喜欢
      • 2012-11-14
      • 1970-01-01
      • 2016-01-04
      • 2020-02-07
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 2019-09-17
      相关资源
      最近更新 更多