Rails Postgres与自定义外键有很多很多关系

时间:2016-06-19 16:35:08

标签: ruby-on-rails ruby-on-rails-4

我有一个事实表,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个商机?

1 个答案:

答案 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