They default way in rails 4 to add foreign keys is simply
add_reference :people, :user
And this will add a column user_id
to the people
table, if the table exists. I have been looking in the rails code where this is handled, and it is really straightforward.
Note that standard rails does not really do anything for referential integrity, it creates the correct columns and an index if so specified.
But we use the schema_plus gem, for two reasons:
So, with schema_plus
, if you write something like:
add_reference :people, :owner
and there is no owners
table, this will give an error.
So instead you need to write :
add_reference :people, :owner, references: :users
This will correctly generate an owner_id
which is a foreign key to users(id)
.
If you want to create a self-referential link, that is really easy. Just write
add_reference :people, :parent
This will create a self-referential link. Awesome :)
For completeness, the add_reference
will add a reference columns to an already existing table. The same can be done when creating (or changing) a table with the following syntax:
create_table :people do |t|
t.references :owner, references: :users
t.references :parent
end
So, in short, if you were not using the schema_plus
gem already, start doing so now :)
Comments
Add comment