Say a model has two children models of the same type, but two different classifications, for example a Shop
has two ShippingOptions
, but one is international and one local
In other words, you know it will always have exactly two, one international and one local,
is it good practice, or even possible to do the following:
shop.rb
has_one :shipping_option, :as => :international_shipping_option
has_one :shipping_option, :as => :local_shipping_option
Otherwise, how should this be handled (best practice)
They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.
A has_one association indicates that one other model has a reference to this model. That model can be fetched through this association. This relation can be bi-directional when used in combination with belongs_to on the other model.
has_one means that there is a foreign key in another table that references this class. So has_one can ONLY go in a class that is referenced by a column in another table. For a two-way association, you need one of each, and they have to go in the right class. Even for a one-way association, it matters which one you use.
It's completely normal to do that, but you've chosen the wrong syntax.
You're after a belongs_to
, and you need to use your "as" option as the name of the association, and specify an explicit class name:
belongs_to :international_shipping_option, class_name: 'ShippingOption'
belongs_to :local_shipping_option, class_name: 'ShippingOption'
The name of the association maps to the foreign key, so you should have two columns called international_shipping_option_id
and a local_shipping_option_id
in your shop
table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With