Ruby on Rails Monday, June 2, 2014

I have the following models

    class Parent < ActiveRecord::Base
      has_many :children
    end

    class Child < ActiveRecord::Base
     belongs_to :parent
    end

What I want to do is changing a child object by parent.children.find_or_initialize_by() and modify the child object, then save it by parent.save. But the children doens't get saved. Here's the code.

    # prepare a parent with a child
    p = Parent.new({:name=>'parent'})
    p.children << Child.new({:name => 'child'})
    p.save

    # modify and save child
    p = Parent.first
    c = p.children.find_or_initialize_by({:name=>'child'}) #=> returns the child already created above
    c.name = 'new child'
    p.save #=> children aren't saved

I know this is because find_by method always returns a new object rather than the one already loaded. But it seems more natural to me if the code above works because the method is invoked through ActiveRecord::Associations::CollectionProxy. Am I missing anything to get this to work? Or are there any reasons that find_by on ActiveRecord::Associations::CollectionProxy have to work as it currently does?

(I know I can save the modified child by c.save, but I want to save the child through parant.save, because I want the errors on child object to be referenced by parent.errors.)

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/241953d4-e0f9-49cd-a51e-f331b20b31a4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment