John
John

Reputation: 1

Rails foreign key

I'm not sure if I fully wrap my mind around this. I want to create a relationship between stores and documents.

In the document table I want a reference to the store and account that created it. To do this would I run this migration

rails g AddStoreToDocuments store:references

and then in the model, specify foreign_keys of account_id and store_id?

like this?

has_many :stores, foreign_key: "store_id"

What is the correct way?

Upvotes: 0

Views: 110

Answers (4)

Pramod
Pramod

Reputation: 1416

I suggest you to read rails guide on migration.

You can generate the reference by using

rails g migration AddStoreRefToDocuments store:references
rake db:migrate

This will generate the migration. Your models should have association mentioned to make it work

Class Store < ActiveRecord::Base
  has_many :documents
end

Class Document < ActiveRecord::Base
  belongs_to :store
end

Upvotes: 2

Gerry
Gerry

Reputation: 10497

In the document table I want a reference to the store and account that created it.

Your relationship should be belongs_to instead of has_many:

belongs_to :store
belongs_to :account

Notice that, since you are following ActiveRecord conventions, you don't need to specify any foreign key (it will use store_id and account_id).

And has_many relationship should be used in both Store and Account models:

has_many :documents

You will also need to update your migration (or create a new one) to add account:references.

Upvotes: 1

Nitin
Nitin

Reputation: 7366

Your documents table should have reference to both tables.

rails g AddStoreToDocuments store:references account:references

relation should be store has_many documents and account has_many documents. So in Document model :

belongs_to :store
belongs_to :account

in Store model :

has_many :documents

in Account model :

has_many :documents

Upvotes: 1

Md. Farhan Memon
Md. Farhan Memon

Reputation: 6121

firstly, your migration would throw an error, it should be

rails g migration AddStoreToDocuments store:references

generated migration looks like

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

then do,

rake db:migrate

which will automatically create a column store_id in your documents table, so in your documents.rb

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

Upvotes: 0

Related Questions