Reputation: 2064
I'm trying to create a HABTM relationship between to classes User
and Benefit
. The problem is that users and benefits have multiple relationships with each other, so I'm trying to give this relationship a unique name, FavoriteBenefitization
.
Unfortunately when I do User.last.favorite_benefits
I keep getting the error message:
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'favorite_benefitizations.user_id' in 'where clause': SELECT `benefits`.* FROM `benefits` INNER JOIN `favorite_benefitizations` ON `benefits`.`id` = `favorite_benefitizations`.`favorite_benefit_id` WHERE `favorite_benefitizations`.`user_id` = 6088
Here is the code I used:
class FavoriteBenefitization < ActiveRecord::Base
belongs_to :favorited_user, :class_name => 'User'
belongs_to :favorite_benefit, :class_name => 'Benefit'
validates :favorited_user, :favorite_benefit, :presence => true
end
class User < ActiveRecord::Base
has_many :favorite_benefitizations,
:dependent => :destroy
has_many :favorite_benefits,
:through => :favorite_benefitizations
end
class Beneift < ActiveRecord::Base
has_many :favorite_benefitizations,
:dependent => :destroy
has_many :favorited_users,
:through => :favorite_benefitizations
end
This is for an application running Rails 3.1
Any help would be awesome. Thank you!
Upvotes: 1
Views: 669
Reputation: 2668
FavoriteBenefitization is a join table here and as such you should use user_id and benefit_id as the column names. In your other models you can do fancy things like renaming associations, scopes, or creating new ones by identifying foreign keys and classes, etc.
for example, I have this in my Message model: has_one :recipient, :foreign_key => "id", :primary_key => "receiver_id", :class_name => "User"
But Rails expects the join table columns to conform to it's expectations.
Edit: Rails expects this because you are using :through which identifies a join table.
Upvotes: 1