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

Now I'm starting to work on Rails, I looked at the forum, but I did not find anything that could solve my problem.

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

The category is said to have many products.

Then in category models, how can I say that the name is the primary key, and how can I match the name of the primary key in the category and the category in the products?

+8
ruby-on-rails foreign-key-relationship
Nov 30 2018-11-11T00:
source share
2 answers

Foreign key restrictions are not used very often in Active Record, because the Active Record ideology suggests that such logic should belong to the model, and not to 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 identifier column in all tables, including the Categories table, and in your Products table, a column named Category_ID. Note that table names are plural.

Then, in your model, you define the relationship between the Product and Category objects. Read the Active Recording Associations Guide article and it will answer all your questions, especially in sections 2.1, 2.2, and 3.3.

+15
Nov 30 2018-11-11T00:
source share

There are many good reasons for having 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 application.

+6
Dec 02 2018-11-11T00:
source share



All Articles