不知道如何声明这个has_many多态关联

时间:2012-07-02 13:06:15

标签: ruby-on-rails activerecord

我有一个用户模型,可能有很多活动(为了统计目的,我正在跟踪我的用户执行的一些操作)

class User < ActiveRecord::Base
  has_many :activities
  has_many :histories,:through => :activities # ?
end

class Activity < ActiveRecord::Base
  belongs_to :user
  belongs_to :history, :polymorphic => true
end

class BrowsingHistory < ActiveRecord::Base
  has_many :activities,:as => :histories
end

class LoginHistory < ActiveRecord::Base
  has_many :activities,:as => :histories
end

...

Activity班级有history_type:stringhistory_id:integeruser_id:integer,我希望它能够容纳BrowsingHistory或{{1对象。

我在多态关联方面做得很少,而且从我到目前为止,我一直得到错误:LoginHistory。我读了一些关于这个主题的相关问题,但我无法找到解决方案。

编辑:我想我得到了(控制台测试似乎有效),请你确认一下吗?

ActiveRecord::HasManyThroughAssociationPolymorphicSourceError:Cannot have a has_many :through association 'User#histories' on the polymorphic object 'History#history'

1 个答案:

答案 0 :(得分:3)

这很好用:

class User < ActiveRecord::Base
  has_many :activities
  has_many :login_histories,:through => :activities,:source => :history,:source_type => "LoginHistory"
end

class Activity < ActiveRecord::Base
  belongs_to :user
  belongs_to :history, :polymorphic => true
end

class BrowsingHistory < ActiveRecord::Base
  has_many :activities,:as => :history
  has_many :users,:through => :activities
end

class LoginHistory < ActiveRecord::Base
  has_many :activities,:as => :history
  has_many :users,:through => :activities
end