Ruby Rails 记录关联(has_many :through)

Ruby Rails Record Associations(has_many :through)

您好,我正在使用 ruby rails 创建 3 个模型 但我有一些问题。 这是我的模型代码

class Company < ActiveRecord::Base
    has_many :pendings
    has_many :products, :through => :pendings
end

class Product < ActiveRecord::Base
  has_many :pendings
  has_many :companies, :through => :pendings
end

class Pending < ActiveRecord::Base
  belongs_to :company
  belongs_to :product
end

我想让公司可以通过 Pending 拥有很多产品,反之亦然,效果很好,但是有什么办法可以在公司和产品之间只设置 1 个待定模型。

Here's my currently model

I want to make it like this

一个选项:您可以保留关联,但将以下验证添加到 pending.rb

validates :company_id, uniqueness: {scope: :product_id}

在此处查看更多信息:rails validation docs

这将确保每个公司和产品只能有一个待处理...但公司在其他产品方面有很多待处理。