我有一个事实表,clients
包含许多业务:
bus_id, sales, date
1, $986, 1/1/2016
1, $543, 1/2/2016
2, $921, 1/1/2016
2, $345, 1/2/2016
我想创建一个表opportunities
bus_id, opportunity
1, "Upsell"
1, "Upsell More"
如何创建opportunities
表格,以便显示每bus_id
个商机?
答案 0 :(得分:1)
这是迁移命令:
bin/rails g model opportunity custom_foreign_bus_id:integer:index description
<强> businesses.rb 强>
has_many :opportunities, foreign_key: :custom_foreign_bus_id
<强> opportunity.rb 强>
belongs_to :business, foreign_key: :custom_foreign_bus_id
然后获得商机:
Business.find(1).opportunities
或简单地说:
Opportunity.where(custom_foreign_bus_id: 1)
要做多对多,您需要has_and_belongs_to_many
关联或加入模式,这是您真正想要的吗?
2.8 Choosing Between has_many :through and has_and_belongs_to_many