Reputation: 10021
I have 2 models:
Account
Profile
creating these models created 2 tables in the database:
accounts
profiles
now I want to add a relationship:
I ran the following command:
rails g migration AddAccountToProfiles account:references
which created the following migration:
class AddAccountToProfiles < ActiveRecord::Migration
def change
add_reference :profiles, :account, index: true, foreign_key: true
end
end
now I'm a little confused:
why does the migration say :profiles
and :account
? Shouldn't it be :accounts
(plural)?
also, after (or before) creating this migration, I have to add belongs_to
and has_many
in the appropriate model class right?
as a side question, is there a way to add belongs_to
and has_many
in the models, and from that information have rails generate the appropriate migration without me manually creating a migration with the 'rails g migration ...'
command?
Upvotes: 4
Views: 4002
Reputation: 4813
The migration is correct, because a profile only belongs to one account. It should not be 'accounts'. The migration will place a account_id
column onto the profiles table in order to make that connection.
After the migration, you still need to add has_many
and belongs_to
. In Rails, when defining a relationship, there are generally two steps 1) create the database migration 2) define the relation on the model class itself. You need to have both. In this case, Rails is looking for the account_id
column on a profile (the default foreign key) to make the relationship between the two models.
And as for your last question, no, there is not a way to generate migrations after defining a has_many
. You can use Rails generators to create the model itself rails generate model ModelName
and define the relationship in that model; that will add the correct belongs_to
and has_many
into the generated model along with the migration. But in practice, it's generally better to create the migration and manually add belongs_to
and has_many
as needed so there's less of a chance of missing something.
Upvotes: 1
Reputation: 1930
As per rails documentation, the command
rails g migration AddAccountToProfiles account:references
will generate the migration file below
class AddAccountToProfiles < ActiveRecord::Migration
def change
add_reference :profiles, :account, index: true, foreign_key: true
end
end
Since you specified account:references
, then it assumes to create account_id
on profiles
table, but you still need to add the relationships in the corresponding model files.
When we use :accounts
in migration file, it's referring to the table in the database, :account
is used as the name of the foreign key to be added onto the table along with suffix _id
Also relevant information here
Upvotes: 4