2017-06-15 24 views
0

これについて私が完全に私の心を包み込むかどうかはわかりません。 storesdocumentsの間に関係を作成したいと思います。Railsの外部キー

文書表では、作成したstoreおよびaccountへの参照が必要です。行うにはこれは私がこの移行

rails g AddStoreToDocuments store:references 

を実行し、モデルに、account_idstore_idforeign_key Sを指定する?う

このような?

has_many :stores, foreign_key: "store_id" 

正しい方法は何ですか。原稿台に

答えて

1

私はそれを作成しstoreaccount への参照をしたいです。あなたはActiveRecordの規則に従っていることから、あなたが任意の外部キーを指定する必要はありません、ということ

belongs_to :store 
belongs_to :account 

は注意してください(それはstore_idaccount_idを使用します):あなたの関係ではなくhas_manybelongs_toでなければなりません

そして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 g migration AddStoreRefToDocuments store:references 
rake db:migrate 

を用いて基準を生成することができますが、rails guide on migration.

を読むことをお勧めします。あなたのモデルには、動作させるための関連付けがあるはずです

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ドキュメントとaccount has_manyドキュメントを格納する必要があります。だから、ドキュメントモデルで :

has_many :documents 

アカウントモデルで:

has_many :documents 
ストアモデルで

belongs_to :store 
belongs_to :account