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>]