has_one 来自模型属性而不是外键

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

我希望有一个基于我的产品属性而不是其 ID 的

has_one
关系。

class Pricing
  belongs_to :type
  belongs_to :brand
  validates :type_id, uniqueness: { scope: :brand_id }
end


class Product
  belongs_to :type
  belongs_to :brand

  has_one :pricing # I need to indicate that the matching pricing is the one that has the same brand and type than my product.
end

在这种情况下我们如何建立

has_one
关系?

ruby-on-rails activerecord has-one
1个回答
0
投票

为这种情况添加

has_one
API 并没有真正的意义,代码中支持这种不寻常的需求所需的扭曲会使代码变得非常复杂。

除了 getter 之外,你似乎不太可能想要任何东西,所以你自己写一下:

def pricing = Pricing.find_sole_by type: type, brand: brand
© www.soinside.com 2019 - 2024. All rights reserved.