我有一个User
和一个Shop
模型(Rails 5.2)应该有多个位置,如ship_location
,bill_location
...我怎么能多次使用相同的Location
?
User
和Shop
模型可能看起来像这样
class User
has_one :ship_location
has_one :bill_location
end
class Shop
has_one :ship_location
has_one :bill_location
has_one :contact_location
end
但我无法弄清楚Location
模型应该是什么样子。它应该尽可能抽象,因此当Location
用于另一个模型时,我不必定义新的关系和/或模型。
我想我必须使用某种多态性:
class Location
# location has owner_id and owner_type
belongs_to :owner, polymorphic: true
end
但这不起作用,因为user.ship_location
是模糊的(它会寻找owner_type == "User"
和owner_id == 1
,但因为还有一个bill_location
与owner_type
和owner_id
相同,它不起作用)。
我是否需要为此创建单独的模型,它们共享同一个表?
1 =>在location_type
模型中取一列(让我们说shipping location
或任何可以在billing location
,contact location
和Location
之间产生差异的列)
class User
has_one :ship_location, -> { where("location_type = ?", 'ship') }, :class_name => "Location", :dependent => :destroy
has_one :bill_location, -> { where("location_type = ?", 'bill') }, :class_name => "Location", :dependent => :destroy
end
class Shop
has_one :ship_location, -> { where("location_type = ?", 'ship') }, :class_name => "Location", :dependent => :destroy
has_one :bill_location, -> { where("location_type = ?", 'bill') }, :class_name => "Location", :dependent => :destroy
has_one :contact_location, -> { where("location_type = ?", 'contact') }, :class_name => "Location", :dependent => :destroy
end
class Location
belongs_to :user
belongs_to :shop
# (has column 'location_type')
end
2 =>创建位置时提供它各自的值(即ship
,bill
,contact
)示例 - >让我们说为location
= loation_type
创建bill
Location.create(location_type: 'ship', foo: 'bar' ...)