Rails PG HABTM 关系 [英] Rails PG HABTM relationship

查看:38
本文介绍了Rails PG HABTM 关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想创造一个表机会

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

如何在两者之间创建具有 has_and_belongs_to_many 关系的机会表,以便它们在 bus_id 外键上链接?

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?

推荐答案

首先为他们创建一个连接模型:

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

那么:

models/business.rb

has_and_belongs_to_many :opportunities

models/opportunity.rb

has_and_belongs_to_many :businesses

这将做的是为每个模型添加一个动态"属性,将 ID 存储到一个数组中.

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

示例:

#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

这篇关于Rails PG HABTM 关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆