我有一个用户模型,它可能有很多活动(出于统计目的,我正在跟踪我的用户执行的一些操作)
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
有 a history_type:string
、 ahistory_id:integer
和 a user_id:integer
,我希望它能够容纳BrowsingHistory
或LoginHistory
对象。
我在多态关联方面的工作很少,从我到目前为止的情况来看,我一直收到错误:ActiveRecord::HasManyThroughAssociationPolymorphicSourceError:Cannot have a has_many :through association 'User#histories' on the polymorphic object 'History#history'
. 我阅读了有关该主题的一些相关问题,但我无法找到解决方案。
编辑:我想我明白了(控制台测试似乎有效),你能确认一下吗?
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