2016-06-21 9 views
1

ich eine Faktentabelle haben, Kunden mit einer Reihe von Unternehmen:Rails PG HABTM Beziehung

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

Ich möchte

eine Tabelle Chancen
bus_id, opportunity 
    1,  "Upsell" 
    1, "Upsell More" 

So erstellen erstelle ich die Möglichkeiten Tisch mit ein has_and_belongs_to_many Beziehung zwischen den beiden, so dass sie auf dem Fremdschlüssel bus_id verknüpft sind?

+0

Sind Sie über die Verbände zu fragen oder die Wanderungen oder beides? –

+0

Wenn die Migrationen nur die Spaltennamen und Datentypen sind, dann die Assoziationen. Meine größte Sorge ist, dass bus_id in beiden Tabellen kein PK ist? – HoosierCoder

+0

erklären Sie den Anwendungsfall – DennisCastro

Antwort

1

Erstellen Sie zunächst eine Join-Modell für sie:

bin/rails g migration create_businesses_opportunities 

Nun gehen Sie auf die Migrationsdatei und stellen Sie sicher, dass es wie folgt aussieht:

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 

Dann:

models/business.rb

has_and_belongs_to_many :opportunities 

Modelle/opportunity.rb

has_and_belongs_to_many :businesses 

Was wird dies für jedes Modell eines ‚dynamisch‘ Attribut zu tun ist hinzuzufügen, dass der IDs in ein Array gespeichert werden.

Beispiel:

#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

Große Antwort mit Controller-Nutzung als auch, danke! – HoosierCoder

Verwandte Themen