This project is archived and is in readonly mode.

#3600 ✓invalid
Luke Mcildoon

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

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>

Pages