Rails:Polymorphic has_many:通过变通办法

时间:2013-06-25 22:59:45

标签: ruby-on-rails has-many-through polymorphic-associations

我的应用程序允许用户遵循多种不同的模型类型,包括其他用户,组织,产品等。每个模型都有一个has_many :: histories关联。我的目标是编译current_user所遵循的所有资源的历史记录。

我的模特看起来像这样:

class Follow < ActiveRecord::Base
  belongs_to :user
  belongs_to :followable, polymorphic: true
end

class History < ActiveRecord::Base
  belongs_to :historical, polymorphic: true
end

class User < ActiveRecord::Base
  has_many :follows
  has_many :followed_resources, through: :follows, source: :followable
  has_many :followed_histories, through: :followed_resources, source: :histories

  has_many :followings, class_name: "Follow", as: :followable
  has_many :histories, as: :historical
end

class Product < ActiveRecord::Base
  has_many :followings, class_name: "Follow", as: :followable
  has_many :histories, as: :historical
end

class Organization < ActiveRecord::Base
  has_many :followings, class_name: "Follow", as: :followable
  has_many :histories, as: :historical
end

etc

我的目标是从所有current_user的跟踪资源中获取历史记录:

@histories = current_user.followed_histories

但不幸的是,Rails不允许我们在has_many:through关系中遍历多态关联。相反,它坚持我们使用source_type选项仅指定一个关联。例如

has_many :followed_products, through: :follows, source: :followable, source_type: :product

不幸的是,这种方法在这种情况下不起作用,除非有一些方法可以在之后重新组合所有关联。例如,如果有某种方法可以做到这一点:

has_many :followed_histories, through: {:followed_products, :followed_organizations, :followed_users}

或许还有另一种我不考虑的方法。我愿意接受任何建议,只要最终结果是包含所跟随资源的组合历史的单个数组。

0 个答案:

没有答案