问题描述
如何为具有对同一模型的两个引用的模型创建迁移.
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
希望这有帮助!
这篇关于两个所属关联迁移的相同模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!