4

別のモデルオブジェクト(子)にhas_manyアソシエーションを持つモデルオブジェクト(たとえば親)があります。

class Parent < ActiveRecord::Base
    has_many :children
    accepts_nested_attributes_for :children
end

class Child < ActiveRecord::Base
    belongs_to :parent
end

親では、before_updateコールバックにコードを追加して、その子に基づいて計算された属性を設定します。

私が遭遇した問題は、メソッドParent.update(id、atts)を使用して、新しい子のattsを追加すると、attsコレクションに追加されたものがbefore_update中に使用できないことです(self.childrenは古いコレクションを返します) 。

accepts_nested_attributes_forをいじらずに新しいものを取得する方法はありますか?

4

1 に答える 1

3

あなたが説明することは、Rails2.3.2でうまくいきます。親の子にきちんと割り当てられていないのではないかと思います。更新後に子は更新されますか?

質問で使用されているように、accepts_nested_attributes_forは、親にchild_attributesライターを作成します。:children_attributesではなく:childrenを更新しようとしているように感じます。

これは、説明されているモデルと次のbefore_updateコールバックを使用して機能します。

before_update :list_childrens_names
def list_childrens_names
  children.each{|child| puts child.name}
end

コンソールのこれらのコマンド:

Parent.create # => Parent(id => 1)
Parent.update(1, :childrens_attributes => 
  [{:name => "Jimmy"}, {:name => "Julie"}]) 

この出力を生成します:

Jimmy
Julie
于 2010-01-07T15:49:25.603 に答える