gpt4 book ai didi

sql - ActiveRecord has_many 通过多态 has_many

转载 作者:数据小太阳 更新时间:2023-10-29 07:39:27 26 4
gpt4 key购买 nike

看来 rails 仍然不支持这种类型的关系并抛出 ActiveRecord::HasManyThroughAssociationPolymorphicThroughError 错误。

我该怎么做才能实现这种关系?

我有以下联想:

Users 1..n Articles
Categories n..n Articles
Projects 1..n Articles

这是订阅模式

Subscription 1..1 User
Subscription 1..1 Target (polymorphic (Article, Category or User))

而我需要根据user#subscriptions通过Subscription#target#article来选择文章。

我不知道如何实现这个

理想情况下我想获得关联类的实例

更新 1

举个例子

假设 user_1 有 4 条订阅记录:

s1 = (user_id: 1, target_id: 3, target_type: 'User')
s2 = (user_id: 1, target_id: 2, target_type: 'Category')
s3 = (user_id: 1, target_id: 3, target_type: 'Project')
s4 = (user_id: 1, target_id: 8, target_type: 'Project')

我需要方法 User#feed_articles,它可以获取属于我订阅的任何目标的所有文章。

user_1.feed_articles.order(created_at: :desc).limit(10) 

更新 2

我在用户模型中按类型分隔文章来源:

  has_many :out_subscriptions, class_name: 'Subscription'

has_many :followes_users, through: :out_subscriptions, source: :target, source_type: 'User'
has_many :followes_categories, through: :out_subscriptions, source: :target, source_type: 'Category'
has_many :followes_projects, through: :out_subscriptions, source: :target, source_type: 'Project'

has_many :feed_user_articles, class_name: 'Article', through: :followes_users, source: :articles
has_many :feed_category_articles, class_name: 'Article', through: :followes_categories, source: :articles
has_many :feed_project_articles, class_name: 'Article', through: :followes_projects, source: :articles

但是我怎样才能在不损失性能的情况下合并 feed_user_articles 与 feed_category_articles 和 feed_project_articles

更新 3.1

我发现的唯一方法是使用原始 SQL 连接查询。看起来它工作正常,但我不确定。

  def feed_articles
join_clause = <<JOIN
inner join users on articles.user_id = users.id
inner join articles_categories on articles_categories.article_id = articles.id
inner join categories on categories.id = articles_categories.category_id
inner join subscriptions on
(subscriptions.target_id = users.id and subscriptions.target_type = 'User') or
(subscriptions.target_id = categories.id and subscriptions.target_type = 'Category')
JOIN

Article.joins(join_clause).where('subscriptions.user_id' => id).distinct
end

(这仅适用于用户和类别)

它支持范围和其他功能。唯一让我感兴趣的是:这个查询会导致一些不良影响吗?

最佳答案

我认为从数据库性能的角度来看,使用 UNION ALL 多查询比使用多态多连接更有效。它也将更具可读性。我尝试编写一个 Arel 查询作为示例,但它运行不佳(我未能使 order by 子句正常工作)所以我认为你必须通过原始 SQL 来放置它。除了 ORDER BY 子句之外,您还可以使用 SQL 模板来干燥它。

关于sql - ActiveRecord has_many 通过多态 has_many,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24615493/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com