index: It's there to duplicate a specific column in the table to speed up the search.
Create a user_id column with references: t.references: user and index user_id. (No foreign key constraints)
foreign_key: true: Paste a foreign key constraint. Prevents the id of a non-existent User from being registered in user_id. Prevents mistakes that erase records in the parent table.
add_foreign_key (: articles,: users) will add an index if there is no index, and reuse it if there is one. Therefore, the order of adding foreign key constraints → pasting indexes is not acceptable.
rails g model article body: text user: references
migrationfile.rb
class CreateArticles < ActiveRecord::Migration[5.2]
def change
create_table :articles do |t|
t.text :body
t.references :user, foreign_key: true
t.timestamps
end
end
end
Recommended Posts