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