我有下表“参与”:
id: integer
coupon_id: integer
participant_type: string
participant_id: integer
我有以下型号:
class Participation < ActiveRecord::Base
belongs_to :coupon
belongs_to :participant, :polymorphic => true
belongs_to :group, :class_name => "Group",
:foreign_key => "participant_id"
belongs_to :location, :class_name => "Location",
:foreign_key => "participant_id"
end
class Coupon < ActiveRecord::Base
has_many :partipations, :as => :participant
has_many :groups, :through => :participations, :source => :group,
:conditions => "participants_type = 'Group'"
has_many :locations, :through => :participations, :source => :location,
:conditions => "participants_type = 'Location'"
end
这与此处的文章中所指出的一样,也类似于此处的 ActiveRecord 文档。访问 Coupon.first.groups 或 Coupon.first.locations 时失败,错误如下:
ActiveRecord::HasManyThroughAssociationNotFoundError:
Could not find the association :participations in model Coupon
我尝试了其他一些变化,但没有运气。当然,访问 Group.first.participations 会出现“未定义的方法”错误。