formtastic 嵌套字段的验证
Validation on formtastic nested fields
我的代码中有一对多关联,如下所示:
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 %>
表单正确地填充了嵌套 table 中的数据。
我需要在控制器中进行一些验证,我想将用户指向发生错误的字段。如果我写这样的错误:
errors.add :one_field, "This is wrong"
这没有问题,并将错误放在页面上该字段的右边。但我想对嵌套字段做同样的事情,比如:
errors.add :second.another_field, "Another wrong one"
但是我得到一个错误:
undefined method `another_field' for :second:Symbol
有没有办法在嵌套字段上添加错误?
问题是访问 First 的错误成员。我需要的是:
second.errors.add :another_field, "Another wrong one"
我的代码中有一对多关联,如下所示:
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 %>
表单正确地填充了嵌套 table 中的数据。
我需要在控制器中进行一些验证,我想将用户指向发生错误的字段。如果我写这样的错误:
errors.add :one_field, "This is wrong"
这没有问题,并将错误放在页面上该字段的右边。但我想对嵌套字段做同样的事情,比如:
errors.add :second.another_field, "Another wrong one"
但是我得到一个错误:
undefined method `another_field' for :second:Symbol
有没有办法在嵌套字段上添加错误?
问题是访问 First 的错误成员。我需要的是:
second.errors.add :another_field, "Another wrong one"