两个belongs_to的关联迁移同型号 [英] Same Model for Two belongs_to Associations migration

查看:184
本文介绍了两个belongs_to的关联迁移同型号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何创建一个具有两个引用到相同型号的模型迁移。

How do I create a migration for a model that has two references to the same model.

我有两个角色,买方和卖方的用户模型,我也​​有一个销售模式,所以每个销售应该有一个买家和一个卖方。

I have a user model with two roles, buyer and seller, I also have a sales model so each sale should have one buyer and one seller.

我见过这个答案那就表明我的销售模型应该看起来像

I've seen this answer that would suggest my sales model should look like

class Sale < ActiveRecord::Base
  belongs_to :buyer, :class_name => 'User', :foreign_key => 'buyer_id'
  belongs_to :seller, :class_name => 'User', :foreign_key => 'seller_id'
end

但我不知道如何创建的迁移和得到它的工作...!

but I don't know how to create the migration and get it to work...!

推荐答案

您必须创建以下迁移:

rails g migration AddBuyerAndSellerToSales buyer:references seller:references

这应该创建以下迁移文件:

This should create the following migration file:

class AddBuyerAndSellerToSales < ActiveRecord::Migration
  def change
    add_reference :sales, :buyer, index: true, foreign_key: true
    add_reference :sales, :seller, index: true, foreign_key: true
  end
end

如果您使用的数据库引擎如PostgreSQL,你必须告诉引擎哪个表的外键将指向。

If you use a database engine like PostgreSQL you have to tell the engine to which table the foreign key will point.

class AddBuyerAndSellerToSales < ActiveRecord::Migration
  def change
    add_reference :sales, :buyer, index: true   # foreign_key: true <= remove this!
    add_reference :sales, :seller, index: true  # foreign_key: true <= remove this!

    add_foreign_key :sales, :users, column: :buyer_id
    add_foreign_key :sales, :users, column: :seller_id
  end
end

希望这有助于!

这篇关于两个belongs_to的关联迁移同型号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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