ruby-on-rails - 同一个模型的多个 has_one 关系
问题描述
我有User
一个Shop
模型(Rails 5.2),它应该有多个位置,例如ship_location
,bill_location
......我怎样才能Location
多次使用相同的位置?
User
andShop
模型可能看起来像这样
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_type
and 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 => 在创建 Location 时提供它各自的值(即ship
, bill
, contact
)示例 -> 假设location
为 shop for loation_type
=bill
Location.create(location_type: 'ship', foo: 'bar' ...)
推荐阅读
- javascript - 移除组件时强制屏幕阅读器阅读
- emacs - Emacs org 模式:latex 片段的背景颜色(使用 `org-highlight-latex-and-related`):要更改哪个变量?
- python - Python:加载 JSON 时跟踪引号
- databricks - Databricks 中的 CLONE TABLE 是否会在克隆前删除目标表?
- wordpress - 为 Elementor Lottie 小部件设置 SVG 属性
- angularjs - 以角度同时显示三个随机图像
- javascript - 如何修复“nodemon 应用程序崩溃”错误消息?
- python - 如何解决 DataFlow 中的 `('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))`?
- ubuntu - 如何检测菊花链网络中的路由器切换?
- python - 使用 sklearn 进行多项式回归绘图