This project is archived and is in readonly mode.

#3148 ✓stale
laserlemon

Polymorphic belongs_to association isn't fully populated during build

Reported by laserlemon | September 4th, 2009 @ 04:33 PM

With a one-to-many polymorphic association, the build method doesn't work as expected. Given the following models:

class User < ActiveRecord::Base
  has_many :addresses, :as => :addressable
end

class Address < ActiveRecord::Base
  belongs_to :addressable, :polymorphic => true
end

building a new address through the user's has_many association properly populates the addressable_id and addressable_type columns, but returns nil for addressable. Using "new" rather than "build" returns the user as expected.

>> user = User.create(:name => "Steve")
=> #<User id: 1, name: "Steve">
>> new_address = user.addresses.new
=> #<Address id: nil, addressable_id: 1, addressable_type: "User">
>> new_address.addressable
=> #<User id: 1, name: "Steve">
>> built_address = user.addresses.build
=> #<Address id: nil, addressable_id: 1, addressable_type: "User">
>> built_address.addressable
=> nil

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