# Polymorphic and has\_one associations

**URL:** <https://www.ruby-forum.com/t/polymorphic-and-has-one-associations/156936>\
**Category:** Rails\
**Created:** [January 5, 2009, 3:49pm UTC](https://www.ruby-forum.com/t/polymorphic-and-has-one-associations/156936 "2009-01-05T15:49:54Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![kadoudal](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/f0a364/32.png) [@kadoudal](https://www.ruby-forum.com/u/kadoudal)\
**Post date:** [January 5, 2009, 3:49pm UTC](https://www.ruby-forum.com/t/polymorphic-and-has-one-associations/156936/1 "2009-01-05T15:49:54Z")

</div>

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](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
