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