2017-06-15 61 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 
在商店模式