This project is archived and is in readonly mode.
find_or_initialize_by does not add initialized records to associationproxy
Reported by Mathijs Kwik | September 8th, 2008 @ 12:01 AM | in 2.x
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>]
Comments and changes to this ticket
-
Pratik December 20th, 2008 @ 03:41 PM
- Assigned user set to Pratik
- State changed from new to wontfix
I'll reopen once we have a patch.
Thanks.
-
Chris Johnson September 14th, 2010 @ 08:46 PM
- 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.
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>