activerecord - 具有可选关系的联合表
问题描述
我有三个模型:
- 公司;
- 投资者;
- 经纪人。
在现实世界中,每个投资者都可以投资许多公司,但在某些情况下,他/她可以在经纪人的帮助下进行投资。我通过联合表做到了。
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
经纪人不属于投资者,每个公司/投资者对可以是不同的经纪人。
解决方案
通过关联使用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
使用此模型,您可以添加有或没有Investor
的Company
关联Broker
,还可以区分它们。我还建议将连接模型(在我的代码中我命名为CompanyInvestor
)命名为更重要的名称,例如Investment
推荐阅读
- r - R 基础图不显示 xticks 和 yticks
- mongodb - 根据给定文档的值是否在数组中创建具有布尔值的新字段
- python - 如何使用 pandas 过滤 csv 数据文件
- jquery - 如何在 jquery 下拉清单中使用工具提示或标题
- asp.net-core - 如何将证书附加到 DelegatingHandler 的 InnerHandler
- javascript - 如何在 javascript 中使用本地图像?
- javascript - Winston createLogger 自定义函数
- ios - 使用 Xcode 10.3 构建时,NSAttributedString 在 iOS 13 上不可见
- winapi - 使用 Windows API 在 Rust 中打开文件
- expss - expss:加一列总计,加一个变量的总行