Polymorphic and has_one associations


#1

I am trying to implement a simple acts_as_addressable plugin (using
Rails 2.2.2)

it’s up and running, but I would like also to give the possibility to
define specifics business/billing/private addresses for a defined
user… I read (
http://wiki.rubyonrails.org/rails/pages/UnderstandingPolymorphicAssociations)
I should use the following code to place the foreign_key in the owning
association :

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

end

class User
has_many :addresses, :as => :addressable
belongs_to :business_address, :foreign_key =>
‘business_address_id’, :class_name => ‘Address’
belongs_to :billing_address, :foreign_key =>
‘billing_address_id’, :class_name => ‘Address’
end

I can run the following :
business = Address.new(:street1 => “business1”, :city =>
“city1”, :postal_code => “postal_code1”)
user = User.first
user.addresses << business

=> [#<Address id: 1, addressable_id: 1, addressable_type: “User”,
business_address_id: nil, private_address_id: nil, billing_address_id:
nil, street1: “business1”, city: “city1”, postal_code: “postal_code1”,
street2: nil, state: nil, country: “France”>]

but when I run (to set the belongs_to association)
user.business_address = business
I don’t have the user.id in the business_address_id field,… it
should be 1 and not nil ?

=> #<Address id: 1, addressable_id: 1, addressable_type: “User”,
business_address_id: nil, private_address_id: nil, billing_address_id:
nil, street1: “business1”, city: “city1”, postal_code: “postal_code1”,
street2: nil, state: nil, country: “France”>

thanks for your help