Forum: Ruby on Rails Aggregating two objects of the same type

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.
Dan M. (Guest)
on 2006-04-05 01:39
(Received via mailing list)
I would like to have a customer that has references to two addresses,
a billing address and a shipping address.  In a non-rails environment
I would have two keys in the customers table, billing_address_id and
shipping_address_id to reference the addresses.  It appears that
ActiveRecord expects the parent id to reside in the child table,
regardless of whether the relationship is one-to-one or one-to-many.

What would the best approach be to persist this type of data
structure?  I would prefer to avoid  a one-to-many relationship from a
customer to addresses where an address type is used to denote the
shipping or billing address.

Thanks,
Dan
Alex Y. (Guest)
on 2006-04-05 02:40
(Received via mailing list)
Dan M. wrote:
> shipping or billing address.
Something like:

class Customer < ActiveRecord::Base
   belongs_to :shipping_address,
     :foreign_key => "shipping_address_id",
     :class_name => "Address"
   belongs_to :billing_address,
     :foreign_key => "billing_address_id",
     :class_name => "Address"
end
Ashley M. (Guest)
on 2006-04-05 03:13
(Received via mailing list)
On Apr 04, 2006, at 11:37 pm, Alex Y. wrote:

> Something like:
>
> class Customer < ActiveRecord::Base
>   belongs_to :shipping_address,
>     :foreign_key => "shipping_address_id",
>     :class_name => "Address"
>   belongs_to :billing_address,
>     :foreign_key => "billing_address_id",
>     :class_name => "Address"
> end

I was just typing a reply when that came through... I was going to
suggest something similar but the other way round:

class Customer < ActiveRecord::Base
   has_one :shipping_address, :class => "Address", :conditions =>
"address_type = 'shipping'"
   has_one :billing_address, :class => "Address", :conditions =>
"address_type = 'billing'"
end

Guess you can take your pick...

Ashley
This topic is locked and can not be replied to.