我有一个用户模型,可能有很多活动(为了统计目的,我正在跟踪我的用户执行的一些操作)
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:string
,history_id:integer
和user_id:integer
,我希望它能够容纳BrowsingHistory
或{{1对象。
我在多态关联方面做得很少,而且从我到目前为止,我一直得到错误:LoginHistory
。我读了一些关于这个主题的相关问题,但我无法找到解决方案。
ActiveRecord::HasManyThroughAssociationPolymorphicSourceError:Cannot have a has_many :through association 'User#histories' on the polymorphic object 'History#history'
答案 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