Rails has_one ,: as => (best practice)

Suppose a model has two child models of the same type, but two different classifications, for example, Shop has two ShippingOptions , but one of them is international and one local

In other words, you know that it will always have exactly two, one international and one local,

it is good practice or it is 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 it should be handled (best practice)

+7
ruby-on-rails ruby-on-rails-3
source share
1 answer

This is fine, but you have chosen the wrong syntax.

You are after belongs_to , and you need to use the β€œlike” option as the name of the association and specify the explicit class name:

 belongs_to :international_shipping_option, class_name: 'ShippingOption' belongs_to :local_shipping_option, class_name: 'ShippingOption' 

The association name maps to a foreign key, so you should have two columns named international_shipping_option_id and local_shipping_option_id in the shop table.

+15
source share

All Articles