首页 > 解决方案 > 同一个模型的多个 has_one 关系

问题描述

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

UserandShop模型可能看起来像这样

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"andowner_id == 1但因为也有 abill_location具有相同的owner_typeand owner_id,所以它不起作用)。

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

标签: ruby-on-railsactiverecordruby-on-rails-5

解决方案


1 => 在模型中取一列(假设或任何可以在、和location_type之间产生差异的列)shipping locationbilling 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 => 在创建 Location 时提供它各自的值(即ship, bill, contact)示例 -> 假设location为 shop for loation_type=bill

Location.create(location_type: 'ship', foo: 'bar' ...)

推荐阅读