Add a reference column to a table
suggest changeTo add a reference to a team to the users table, run this command:
$ rails generate migration AddTeamRefToUsers team:references
This generates the following migration:
class AddTeamRefToUsers < ActiveRecord::Migration[5.0]
def change
add_reference :users, :team, foreign_key: true
end
end
That migration creates a team_id column in the users table. In Rails 5, add_reference also adds an index, and foreign_key: true adds a foreign key to teams.
To set the index and foreign key explicitly:
class AddTeamRefToUsers < ActiveRecord::Migration[5.0]
def change
add_reference :users, :team, index: true, foreign_key: true
end
end
To name the reference column something other than the referenced table, set the foreign key’s table. For example, the user who created a post can be stored as author_id:
class AddAuthorRefToPosts < ActiveRecord::Migration[5.0]
def change
add_reference :posts, :author, foreign_key: { to_table: :users }, index: true
end
end
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents