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

前端 未结 2 1844
忘了有多久
忘了有多久 2021-01-02 12:13

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 n

相关标签:
2条回答
  • 2021-01-02 12:28

    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.

    0 讨论(0)
  • 2021-01-02 12:36

    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.

    0 讨论(0)
提交回复
热议问题