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.

has_many :through association.build doesn't create the :through models

#3600

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

Reported by Luke Mcildoon · December 19th, 2009 @ 03:21 AM

State: invalid
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. Luke Mcildoon
    Luke Mcildoon

    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?

    December 19th, 2009 @ 07:38 AM

  2. Luke Mcildoon
    Luke Mcildoon

    The patch I made has caused a test to fail, so I'm assuming this behaviour is by design. Please ignore/close this ticket.

    December 22nd, 2009 @ 02:04 AM

  3. Rohit Arondekar
    Rohit Arondekar
    • State changed from new to invalid

    June 15th, 2010 @ 12:13 PM