2017-06-15 80 views
0

我不确定我是否完全包围了这一点。我想创建storesdocuments之间的关系。Rails外键

在文档表中我想要参考创建它的storeaccount。要做到这一点,我会运行此迁移

rails g AddStoreToDocuments store:references 

,然后在模型中,指定foreign_key S的account_idstore_id

这样吗?

has_many :stores, foreign_key: "store_id" 

什么是正确的方法?

回答

1

在文档表格我想在storeaccount 创建它的参考。

你的关系应该是belongs_to而不是has_many

belongs_to :store 
belongs_to :account 

注意,因为你是下面的ActiveRecord约定,你不需要指定任何外键(它将使用store_idaccount_id) 。

而且has_many关系应能在两个StoreAccount车型上:

has_many :documents 

您还需要更新您的迁移(或创建一个新的)添加account:references

0

首先,您的迁移会抛出一个错误,它应该是

rails g migration AddStoreToDocuments store:references 

产生迁移看起来像

def change 
    add_reference :documents, :store, index: true, foreign_key: true 
end 

那么做,

rake db:migrate 

它会自动创建一个列您的documents表中有store_id,因此在您的documents.rb

belongs_to :store 
belongs_to :account #this you might already be having I suppose 
2

我建议你阅读rails guide on migration.

您可以生成参考使用

rails g migration AddStoreRefToDocuments store:references 
rake db:migrate 

,这将产生迁移。您的模型应该提到关联使其工作

Class Store < ActiveRecord::Base 
    has_many :documents 
end 

Class Document < ActiveRecord::Base 
    belongs_to :store 
end 
1

您的文档表应该有两个表的引用。

rails g AddStoreToDocuments store:references account:references 

关系应该存储has_many文件和帐户has_many文件。 所以在文档模型:

has_many :documents 

在账户模式:

has_many :documents 

belongs_to :store 
belongs_to :account 
在商店模式