Forum: Ruby on Rails polymorphic and has_one associations

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ee0293412faca21e4ebf3326ed9d5f8c?d=identicon&s=25 Kad Kerforn (kadoudal)
on 2009-01-05 15:49
(Received via mailing list)
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/Understand...)
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
This topic is locked and can not be replied to.