首页 > 解决方案 > 具有可选关系的联合表

问题描述

我有三个模型:

在现实世界中,每个投资者都可以投资许多公司,但在某些情况下,他/她可以在经纪人的帮助下进行投资。我通过联合表做到了。

def change
  create_join_table :companies, :investors do |t|
    t.references :broker, index: true, optional: true
  end
end

class Company < ApplicationRecord
  has_and_belongs_to_many :investors
end

class Investor < ApplicationRecord
  has_and_belongs_to_many :companies
end

class Broker < < ApplicationRecord
  has_many :companies
end

我应该如何配置我的模型/迁移以获得下一个信息:

Company.first.investors.first.broker

经纪人不属于投资者,每个公司/投资者对可以是不同的经纪人。

标签: activerecordruby-on-rails-5

解决方案


通过关联使用has_many 并在连接模型上添加代理。添加正确的迁移后,您的模型将如下所示:

class Company < ApplicationRecord
  has_many :company_investors
  has_many :investors, through: :company_investors
end

class Investor < ApplicationRecord
  has_many :company_investors
  has_many :companies, through: :company_investors
end

class Broker < ApplicationRecord
  has_many :company_investors
  has_many :companies, through: :company_investors
end

class CompanyInvestor < ApplicationRecord
  belongs_to :broker
  belongs_to :investor
  belongs_to :company
end

使用此模型,您可以添加有或没有InvestorCompany关联Broker,还可以区分它们。我还建议将连接模型(在我的代码中我命名为CompanyInvestor)命名为更重要的名称,例如Investment


推荐阅读