开发者

Problem with Polymorphic has_many

I have the following table "participations":

id: integer
coupon_id: integer
participant_type: string
participant_id: integer

and I have the following models:

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

This is as indicated in the article here and is also similar to the ActiveRecord documentation here. It fails miserably when accessing Coupon.first.groups or Coupon.first.locations with the error:

ActiveRecord::HasManyThroughAssociationNotFoundError: 
Could not find the association :participations in model Coupon

I tried some other variations, but with no luck. And 开发者_高级运维of course, accessing Group.first.participations gives an "undefined method" error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜