2016-06-21 84 views
1

我有一個事實表,帶着一幫企業客戶:Rails的PG HABTM關係

bus_id, sales, date 
    1, $986, 1/1/2016 
    1, $543, 1/2/2016 
    2, $921, 1/1/2016 
    2, $345, 1/2/2016 

我想創建一個表的機會

bus_id, opportunity 
    1,  "Upsell" 
    1, "Upsell More" 

如何創造的機會表一個has_and_belongs_to_many兩者之間的關係,以便它們在bus_id外鍵上鍊接?

+0

你是問有關協會或遷移或兩者兼而有之? –

+0

如果遷移只是上面的列名稱和數據類型,那麼就是關聯。我最關心的是bus_id不是任何一個表中的PK? – HoosierCoder

+0

解釋用例 – DennisCastro

回答

1

首先創建一個連接模型爲他們:

bin/rails g migration create_businesses_opportunities 

現在,到遷移文件,並確保它看起來是這樣的:

class CreateBusinessesOpportunities < ActiveRecord::Migration 
    def change 
    create_table :businesses_opportunities do |t| 
     t.belongs_to :opportunity, index: true 
     t.belongs_to :business, index: true 
    end 
    end 
end 

然後:

型號/ business.rb

has_and_belongs_to_many :opportunities 

型號/ opportunity.rb

has_and_belongs_to_many :businesses 

屬性將在IDS存儲到陣列中的每個模型是什麼,這將做的是增加一個「動態」。

例子:

#To have an opportunity belong to multiple businesses, say IDs 1, 2, and 3 
@opp = Opportunity.find(1) 
@opp.update_attribute :business_ids, [1,2,3] 
@opp.businesses 
    # => will now show the three businesses 

#The same works for associating a business to multiple opportunities, just the other way around 
@busn = Business.find(1) 
@busn.update_attribute :opportunity_ids, [1,2,3] 
@busn.opportunities 
    # => will now show the three opportunities 
+1

控制器用法也很好的答案,謝謝! – HoosierCoder