我有一个用户模型,可能有很多 Activity (出于统计目的,我一直在跟踪用户执行的某些操作)

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,我希望它能够容纳BrowsingHistoryLoginHistory对象。

我几乎没有处理多态关联,到目前为止,我仍然收到错误消息: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

最佳答案

这工作正常:

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

关于ruby-on-rails - 不确定如何声明此has_many多态关联,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11294314/

10-11 06:39