ruby on rails - activemodel - updating children of object when saving parent -


this followup question here: updating child association in activemodel

i'm looking standard/correct way update number of children records associated parent.

lets have parent (connected child table has_many, , :autosave=>true).

obj = parent.first 

now iterate on children, , update them.

obj.each.do |child|     child.remark = "something" end 

i children saved parent, when calling obj.save, explained me in previous question, way update directly, this:

obj.children.first.remark = "something" 

(or save each child, require explicit transaction believe shouldn't used here).

what correct way implement this?

thanks!

*edit : following advice given here, i've added model:

class parent < activerecord::base       has_many :children, :inverse_of => :parent,:autosave=>true       accepts_nested_attributes_for :children 

but still,

x = parent.first c = x.children.first c.remark = "something" x.save    # => doesn't update c 

you want activerecord nested_attributes

class parent   include activemodel::model    accepts_nested_attributes_for :children end 

update children , save parent, should done

edit: have call parent.children first:

irb(main):001:0> x = parent.first   parent load (0.3ms)  select "parents".* "parents" order "parents"."id" asc limit 1 => #<parent id: 1, created_at: "2013-08-07 21:21:10", updated_at: "2013-08-07 21:21:10"> irb(main):002:0> x.children   child load (3.0ms)  select "children".* "children" "children"."parent_id" = ?  [["parent_id", 1]] => #<activerecord::associations::collectionproxy [ ]> irb(main):003:0> x.children.first.remark = "foo" => "foo" irb(main):004:0> x.save    (0.3ms)  begin transaction   sql (2.3ms)  update "children" set "remark" = ?, "updated_at" = ? "children"."id" = 1  [["remark", "foo"], ["updated_at", wed, 07 aug 2013 21:33:04 utc +00:00]]    (0.3ms)  commit transaction => true 

Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -