Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

find_or_initialize_by does not add initialized records to associationproxy

#991

When using find_or_initialize_by on an association, newly created objects don't get added to the association-array. This is the case when using build on an association.

I would expect find_or_initialize_by to do the same, when called on an association. In case this isn't wanted in all cases (I can't think of a reason), it would be nice to have a find_or_build_by method to fill in this behavior.

Resorting to


u.posts.find_by_title('title') || u.posts.build(:title => 'title')

doesn't feel nice


class User < ActiveRecord::Base
  has_many :posts, :dependent => :destroy
end

class Post < ActiveRecord::Base
  belongs_to :user
end

>> u=User.first
=> #<User id: 1, name: "user 1", created_at: "2008-09-07 22:07:35", updated_at: "2008-09-07 22:07:35">

>> u.posts.find_or_initialize_by_title('title')
=> #<Post id: nil, user_id: 1, title: "title", created_at: nil, updated_at: nil>
>> u.posts
=> []

>> u.posts.build(:title => 'title')
=> #<Post id: nil, user_id: 1, title: "title", created_at: nil, updated_at: nil>
>> u.posts
=> [#<Post id: nil, user_id: 1, title: "title", created_at: nil, updated_at: nil>]

Reported by Mathijs Kwik · September 8th, 2008 @ 12:01 AM

State: wontfix
Milestone: 2.x
Assigned to: Pratik Pratik
Importance: none

Activity

  1. Pratik
    Pratik
    • Assigned user set to Pratik
    • State changed from new to wontfix

    I'll reopen once we have a patch.

    Thanks.

    December 20th, 2008 @ 03:41 PM

  2. Chris Johnson
    Chris Johnson
    • Importance changed from to

    +1 I was surprised to find that association.find_or_initialize_by does not behave as association.build.

    Would making this change to find_or_initialize_by break existing code? If so, we could easily create a find_or_build_by method.

    Appreciate feedback.

    September 14th, 2010 @ 08:46 PM

  3. bingbing