Reputation:
I'm using Rails 3 and I've got a one to many association I'm trying to define: A user can have many subject families assigned to him/her, but a subject family can only be assigned to one user.
Here's what I have defined:
class User
has_many :subject_families
class SubjectFamily
belongs_to :assignee, :class_name => "User", :foreign_key => 'assigned_to'
I added a migration that does this:
change_table(:subject_families) do |t|
t.integer :assigned_to
end
I'm getting an exception when I try to do:
u = User.first
s = u.subject_families
Here's the exception:
Invalid column name 'user_id'.: SELECT [subject_families].* FROM [subject_families] WHERE ([subject_families].user_id = 1)
I was expecting this to be using subject_families.assigned_to rather than user_id but lo and behold I was disappointed in this expectation. Can anyone see what I might have missed here? I've googled this a lot and from what I can see this SHOULD work.
Upvotes: 1
Views: 1367
Reputation: 7809
I believe you also need to specify the :foreign_key option on the has_many association declaration in your User model.
class User
has_many :subject_families, :foreign_key => 'assigned_to'
Upvotes: 5
Reputation: 46667
You need to specify :foreign_key => 'assigned_to'
in the has_many
relationship on User
as well.
Upvotes: 2