[RUBY] Add foreign key to column with migrate

I would like to write content that even beginners of programming can understand.

Organize how to add foreign keys to columns for model association when migrating with rails.

The premise is that you want to associate a user with multiple tweets of that user.

◉ Add foreign key to table

To do this, add a column called user_id to the newly created tweets table to store the id of the user who owns the post.

In such cases, add a foreign key column using a data type called reference.

Write the migration file that creates the tweets table like this.

class CreateTweets < ActiveRecord::Migration[5.2]
 def change
   create_table :tweets do |t|
     t.string     :text,                     null: false
     t.references :user, foreign_key: true,  null: false

     t.timestamps
   end
 end
end

t.references: user, foreign_key: true Right here.

t.referencees: user will create a column called user_id. And the index is automatically assigned. The index makes searching easier.

However, it seems that there is a demerit that the writing speed becomes slower at the cost of the advantage that the data reading and acquisition becomes faster.

With this alone, there is no foreign key constraint, so

foreign_key: Add true.

Also, if you want to add a foreign key to an existing table:

class AddColumn < ActiveRecord::Migration[5.0]
 def change
   add_reference :tweets, :user, foreign_key: true
 end
end

By the way, ...

You can add a NOT NULL constraint by writing null: false. Put this constraint when you don't want to store NULL in the value of a database column, that is, when you expect the value of an attribute of a model to be included.

Recommended Posts

Add foreign key to column with migrate
[Ruby on Rails] Add a column with a foreign key constraint
How to delete data with foreign key
[Rails] Add column to devise
How to use a foreign key with FactoryBot ~ Another solution
How to rename a model with foreign key constraints in Rails
Add scripts to distributions created with gradle
Add class only to specific elements with V-for
Try to get redmine API key with ruby
[Java] Article to add validation with Spring Boot 2.3.1.
Add packages to your project with Swift PM
Change the database (MySQL) primary key to any column.
FactoryBot, a solution when played with a foreign key validation
I want to add a reference type column later
Add files to jar files
Migrate from JUnit 4 to JUnit 5
Add a local Swift Package to your project with Swift PM
[Rails] How to write user_id (foreign key) in strong parameter