Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails has_one, :as => (best practice)

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)

like image 588
Marco Prins Avatar asked Apr 02 '14 13:04

Marco Prins


People also ask

How would you choose between Belongs_to and Has_one?

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.

Does rails have one relationship?

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.

Does rails have one ruby?

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.


1 Answers

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.

like image 82
meagar Avatar answered Sep 29 '22 20:09

meagar