2016-11-09 34 views
0

我有一个一对多的关联在我的代码,像这样:验证上formtastic嵌套字段

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 

有没有把一个错误的嵌套字段的方式?

回答

0

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

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