与同一模型的多个has_one关系

问题描述 投票:0回答:1

我有一个User和一个Shop模型(Rails 5.2)应该有多个位置,如ship_locationbill_location ...我怎么能多次使用相同的Location

UserShop模型可能看起来像这样

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_locationowner_typeowner_id相同,它不起作用)。

我是否需要为此创建单独的模型,它们共享同一个表?

ruby-on-rails activerecord ruby-on-rails-5
1个回答
1
投票

1 =>在location_type模型中取一列(让我们说shipping location或任何可以在billing locationcontact locationLocation之间产生差异的列)

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 =>创建位置时提供它各自的值(即shipbillcontact)示例 - >让我们说为location = loation_type创建bill

Location.create(location_type: 'ship', foo: 'bar' ...)
© www.soinside.com 2019 - 2024. All rights reserved.