0

我的应用程序允许用户遵循几种不同的模型类型,包括其他用户、组织、产品等。这些模型中的每一个都有一个 has_many: :histories 关联。我的目标是编译 current_user 所关注资源的所有 :history 。

我的模型如下所示:

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}

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

4

0 回答 0