Reputation: 141
I have models/user.rb
that has association with email_activities
:
class User
.
.
has_many :email_activities
end
and models/email_activity.rb
:
class EmailActivity
.
.
belongs_to :user
end
I am accessing the email_activities
for a particular user
, in my controller like this:
user.email_activities
But this raises error:
ActiveRecord::StatementInvalid Exception: Mysql2::Error: Unknown column 'email_activities.user_id' in 'where clause': SELECT `email_activities`.* FROM `email_activities` WHERE `email_activities`.`user_id` = 1
In schema.rb
, email_activities
table has no user_id
key. To fix that, I generated a migration to add index like this:
def change
add_index :email_activities, :user_id
end
But, running the migration, results in different error:
Mysql2::Error: Key column 'user_id' doesn't exist in table
Can you help me in finding what I am doing wrong?
Upvotes: 0
Views: 52
Reputation: 1078
You're trying to add a user_id
field to the email_activities
table, which makes sense.
However, with your migration you're adding an index to a field that doesn't exist (which is why you are getting that error).
You should instead be adding the field itself.
Use this migration instead:
def change
add_column(:email_activities, :user_id, :integer, default: nil, null: false, after: :id)
end
Upvotes: 0