我正在尝试在类User
和Benefit
之间创建HABTM关系。问题是用户和好处之间存在多种关系,因此我尝试将此关系命名为FavoriteBenefitization
。
不幸的是,当我User.last.favorite_benefits
时,我不断收到错误消息:
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
以下是我使用的代码:
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
这适用于运行Rails 3.1的应用程序
任何帮助都会很棒。谢谢!
答案 0 :(得分:1)
FavoriteBenefitization是一个连接表,因此您应该使用user_id和benefit_id作为列名。在你的其他模型中,你可以做一些奇特的事情,比如重命名关联,范围,或者通过识别外键和类等来创建新的。
例如,我在我的消息模型中有这个:has_one :recipient, :foreign_key => "id", :primary_key => "receiver_id", :class_name => "User"
但是Rails希望连接表列符合它的期望。
编辑:Rails期望这是因为你正在使用:通过它来识别连接表。