This project is archived and is in readonly mode.
has_many :through association.build doesn't create the :through models
Reported by Luke Mcildoon | December 19th, 2009 @ 03:21 AM
Using build on a has_many :through association doesn't create the :through models, though the "end" model is created.
Example code and script/console demonstration:
class Author < ActiveRecord::Base
has_many :users, :through => :user_authors
has_many :user_authors
end
class User < ActiveRecord::Base
has_many :authors, :through => :user_authors
has_many :user_authors
end
class UserAuthor < ActiveRecord::Base
belongs_to :user
belongs_to :author
end
Loading development environment (Rails 2.3.5)
>> user = User.last
=> #<User id: 3, email: "user2@example.com", encrypted_password: "8da617e6f06d3190d10a3d0dee3bc483950d02a0", password_salt: "sAEM7UZkGQhvSbDYFpWQ", reset_password_token: nil, created_at: "2009-12-19 03:00:19", updated_at: "2009-12-19 03:00:19">
>> user.authors
=> []
>> author = user.authors.build(:display_name => "Test Author")
=> #<Author id: nil, display_name: "Test Author", created_at: nil, updated_at: nil>
>> author.users
=> []
>> author.user_id
=> 3
>> author.save
=> true
>> author.users
=> []
>> user.authors
=> [#<Author id: 26, display_name: "Test Author", created_at: "2009-12-19 03:15:06", updated_at: "2009-12-19 03:15:06">]
>> user.reload
=> #<User id: 3, email: "user2@example.com", encrypted_password: "8da617e6f06d3190d10a3d0dee3bc483950d02a0", password_salt: "sAEM7UZkGQhvSbDYFpWQ", reset_password_token: nil, created_at: "2009-12-19 03:00:19", updated_at: "2009-12-19 03:00:19">
>> user.authors
=> []
>> user.user_authors
=> []
Comments and changes to this ticket
-
Luke Mcildoon December 19th, 2009 @ 07:38 AM
It looks like this can be fixed in set_belongs_to_association_for in lib/active_record/associations/association_proxy.rb. Before I submit a patch, is this the best place to add it? Is this behaviour by design? Are there any other considerations I should make?
-
Luke Mcildoon December 22nd, 2009 @ 02:04 AM
The patch I made has caused a test to fail, so I'm assuming this behaviour is by design. Please ignore/close this ticket.
-
Rohit Arondekar June 15th, 2010 @ 12:13 PM
- State changed from new to invalid
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>