I have a Project
migration class like this:
class CreateProjects < ActiveRecord::Migration
def change
create_table :projects do |t|
t.string :title
t.text :description
t.boolean :public
t.references :user, index: true, foreign_key: true
t.timestamps null: false
end
end
end
It creates a column name user_id
in projects table but I want to name the column owner_id
so I can use project.owner
instead of project.user
.
It adds a multi-column index on columns one and two in resources table. The advantage of multi-column index is that it helps when you have a query with conditions on those multiple columns.
If you want you can always use add_index on the fields that you want as foreign keys. Or you can write your migrations in SQL or perhaps even force rails to do the foreign keys somehow. But the thing is you won't even look for a way to do it if you don't know rails is not doing itin the first place.
Foreign keys ensure consistency between related database tables. The current database review process always encourages you to add foreign keys when creating tables that reference records from other tables. Starting with Rails version 4, Rails includes migration helpers to add foreign key constraints to database tables.
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.
You can do it two ways:
#app/models/project.rb
class Project < ActiveRecord::Base
belongs_to :owner, class_name: "User", foreign_key: :user_id
end
OR
$ rails g migration ChangeForeignKeyForProjects
# db/migrate/change_foreign_key_for_projects.rb
class ChangeForeignKeyForProjects < ActiveRecord::Migration
def change
rename_column :projects, :user_id, :owner_id
end
end
then:
$ rake db:migrate
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