Forum: Ruby on Rails Receiving already loaded object from find_by method of ActiveRecord::Associations::CollectionProx

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
09083d9430ebedc23782f93779657695?d=identicon&s=25 Ryo Yamada (Guest)
on 2014-06-02 14:27
(Received via mailing list)
I have the following models

    class Parent < ActiveRecord::Base
      has_many :children

    class Child < ActiveRecord::Base
     belongs_to :parent

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

    # prepare a parent with a child
    p ={:name=>'parent'})
    p.children <<{:name => 'child'})

    # modify and save child
    p = Parent.first
    c = p.children.find_or_initialize_by({:name=>'child'}) #=> returns
child already created above = 'new child' #=> 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
this to work? Or are there any reasons that find_by on
ActiveRecord::Associations::CollectionProxy have to work as it currently

(I know I can save the modified child by, but I want to save the
child through, because I want the errors on child object to
referenced by parent.errors.)
This topic is locked and can not be replied to.