Rails的accept_nested_attributes_for孩子没有父集验证时我试图访问我的父模型。我在has_one上找到了一些有关逆向属性的内容,但是我的Rails 2.3.5无法识别它,所以它一定从未将它放入发布版。我不确定它是否正是我需要的。验证时验证
我想根据父属性有条件地验证孩子。我的父母模型已经创建。如果在父级上update_attributes时没有创建子级,那么它无权访问父级。我想知道如何访问这个父母。它应该很容易,就像parent.build_child设置子模型的parent_id,为什么在构建accept_nested_attributes_for子项时没有这样做?
例如:
class Parent < AR
has_one :child
accepts_nested_attributes_for :child
end
class Child < AR
belongs_to :parent
validates_presence_of :name, :if => :some_method
def some_method
return self.parent.some_condition # => undefined method `some_condition' for nil:NilClass
end
end
我的方式是标准:
<% form_for @parent do |f| %>
<% f.fields_for :child do |c| %>
<%= c.name %>
<% end %>
<% end %>
有了更新方法
def update
@parent = Parent.find(params[:id])
@parent.update_attributes(params[:parent]) # => this is where my child validations take place
end
我有同样的错误作为操作,但是当我尝试这种方法时,我得到了“未知的键(s):before_add”? – Kvass 2011-08-19 16:02:19