Rails PG HABTM的关系

时间:2016-06-21 19:41:50

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

我有一个事实表,客户有很多业务:

  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关系的opportunity表,以便它们在bus_id外键上链接?

1 个答案:

答案 0 :(得分: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