Rails PG HABTM relationship

2019-07-30 08:27发布

问题:

I have a fact table, clients with a bunch of businesses:

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

I want to create a table opportunities

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

How do I create the opportunities table with a has_and_belongs_to_many relationship between the two so that they are linked on the bus_id foreign key?

回答1:

First create a join model for them:

bin/rails g migration create_businesses_opportunities

Now, go to the migration file and make sure it looks like this:

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

Then:

models/business.rb

has_and_belongs_to_many :opportunities

models/opportunity.rb

has_and_belongs_to_many :businesses

What this will do is add a 'dynamic' attribute to each model that will store the ids into an array.

Example:

#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