Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to create a foreign key when creating a table on Rails?

i'm starting now on Rails, i looked in the forum, but i didn't find anything that could solve my problem.

Here it goes, I have a Category table, and it has only name for a column (there is no repetition in categories) so i would like name to be the primary key, then i have a Product table that has name, main_photo, description and i would like to say that a product only has a category, do i need to add a column named category as a foreign key in products?

A Category is suposed to have many products.

Then in category models how do i say that name is the primary Key, and how can i do the correspondence between the suposed primary key name in categories and category in products?

like image 436
Márcio Duarte Avatar asked Nov 30 '11 23:11

Márcio Duarte


People also ask

Do you need foreign keys in Rails?

You do not need a foreign key constraints for ActiveRecord to correctly map the relationships. You can use validations to have the Rails app ensure data integrity.

Is it necessary to have foreign keys in a table?

Note that foreign keys are not mandatory, and a table may have no foreign keys. Conversely, every column in a table may have a foreign key constraint.

How do you create a table with only foreign keys?

To create a new table containing a foreign key column that references another table, use the keyword FOREIGN KEY REFERENCES at the end of the definition of that column. Follow that with the name of the referenced table and the name of the referenced column in parentheses.


2 Answers

Foreign key constraints in Active Record aren't used very often as the ideology behind Active Record says that this kind of logic should belong in the model and not in the database - the database is just a dumb store: http://guides.rubyonrails.org/migrations.html#active-record-and-referential-integrity.

The Rails way is to have an ID column on all tables including your Categories table, and in your Products table, have a column called Category_ID. Notice that the table names are plurals.

Then in your model you define the relationships between the entities Product and Category. Read the article A Guide to Active Record Associations and it will answer all your questions, especially sections 2.1, 2.2 and 3.3.

like image 172
dnatoli Avatar answered Oct 12 '22 06:10

dnatoli


There are many valid reasons to have foreign keys in your database. See Does Rails need database-level constraints?

I recommend Foreigner if you want to easily add foreign keys to your Rails app.

like image 24
tee Avatar answered Oct 12 '22 07:10

tee