Activerecord 具有可选关系的联接表
我有三种型号: 公司 投资者 经纪人 在现实世界中,每个投资者都可以投资于许多公司,但在某些公司,他/她可以在经纪人的帮助下进行投资。 我通过了联席会议Activerecord 具有可选关系的联接表,activerecord,ruby-on-rails-5,Activerecord,Ruby On Rails 5,我有三种型号: 公司 投资者 经纪人 在现实世界中,每个投资者都可以投资于许多公司,但在某些公司,他/她可以在经纪人的帮助下进行投资。 我通过了联席会议 def change create_join_table :companies, :investors do |t| t.references :broker, index: true, optional: true end end class Company < ApplicationRecord has_and_
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
经纪人不属于投资者,在每个公司/投资者对中可以是不同的经纪人。在加入模型中使用并添加经纪人。添加正确的迁移后,您的模型将如下所示:
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
使用此模型,您可以将投资者添加到有经纪人或没有经纪人的公司协会中,还可以区分他们。我还建议将join模型命名,在我的代码中,我将CompanyInvestor命名为一个更重要的名称,如Investment(投资),该名称在我需要时不起作用。我无法直接从company.investor pair company.first.investors.first.Brokery中选择broker。您可以从Investment、investor或company by Investment中选择broker。first.broker,Company.first.investments.first.broker或Investor.first.investments.broker。您还可以从公司和投资者对中获取投资,然后选择该投资的经纪人。您将无法从投资者处获取经纪人,并且满足此条件经纪人不属于投资者。从公司/投资中选择经纪人进行投资。wherecompany:any_Company,investor:any_investor.BrokerRerata:Investment.wherecompany:any_Company,investor:any_investor.first.Broker
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