When you already have users and uploads tables and wish to add a new relationship between them. Then, run the migration using rake db:migrate . This migration will take care of adding a new column named user_id to uploads table (referencing id column in users table), PLUS it will also add an index on the new column.
Migrations should be: Camel cased or Snake cased. start with an action (i.e. create, add, remove, etc) The name of the table should be the last word and it should be plural.
If you are defining your Post
model table, you can set references
, index
and foreign_key
in one line:
t.references :author, index: true, foreign_key: { to_table: :users }
If you are adding references to an existing table, you can do this:
add_reference :posts, :author, foreign_key: { to_table: :users }
Note: The default value for index
is true.
In Rails 4.2+ you can also set foreign keys in the db as well, which is a great idea.
For simple associations this can be done also on t.references
adding foreign_key: true
, but in this case you'll need two lines.
# The migration
add_reference :posts, :author, index: true
add_foreign_key :posts, :users, column: :author_id
# The model
belongs_to :author, class_name: "User"
In rails 4, when using postgresql and the schema_plus gem you can just write
add_reference :posts, :author, references: :users
This will create a column author_id
, which correctly refers to users(id)
.
And in your model, you write
belongs_to :author, class_name: "User"
Note, when creating a new table you can write it as follows:
create_table :things do |t|
t.belongs_to :author, references: :users
end
Note: the
schema_plus
gem in it's entirety is not compatible with rails 5+, but this functionality is offered by the gem schema_auto_foreign_keys (part of schema_plus) which is compatible with rails 5.
Do it manually:
add_column :post, :author_id, :integer
but now, when you create the belongs_to statement, you will have to modify it, so now you have to call
def post
belongs_to :user, :foreign_key => 'author_id'
end
If you aren't using a foreign key, then it doesn't matter what the actual table name of the other table is.
add_reference :posts, :author
As of Rails 5, if you're using a foreign key, you can specify the name of the other table in the foreign key options. (see https://github.com/rails/rails/issues/21563 for discussion)
add_reference :posts, :author, foreign_key: {to_table: :users}
Prior to Rails 5, you should add the foreign key as a separate step:
add_foreign_key :posts, :users, column: :author_id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With