検証時に、子モデルの親モデルにアクセスしようとしています。has_oneで逆プロパティについて何かを見つけましたが、Rails 2.3.5はそれを認識しないため、リリースに組み込まれたことはないはずです。それがまさに私が必要としているものかどうかはわかりませんが。
親の属性に基づいて条件付きで子を検証したいと思います。私の親モデルはすでに作成されています。親のupdate_attributesで子が作成されていない場合、その子は親にアクセスできません。この親にアクセスするにはどうすればよいのでしょうか。parent.build_childのようなものが子モデルのparent_idを設定するのは簡単なはずですが、accepts_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