ActiveRecord has_many通过多态has_many
看来像rails仍然不支持这种类型的关系,并引发ActiveRecord :: HasManyThroughAssociationPolymorphicThroughError错误。ActiveRecord has_many通过多态has_many
我能做些什么来实现这种关系?
我有以下关联:
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))
我需要根据用户订阅#选择通过认购##目标文章的文章。
我不知道烫到理想的情况下实现这个
我希望得到协会类的实例
更新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_category_articles和feed_project_articles feed_user_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查询作为示例,但它不能很好地发挥作用(我没有正确地通过子句进行排序),所以我认为你必须通过原始SQL来进行。您可以使用ORDER BY子句以外的SQL模板来干燥它。
关于order by子句,你是否把它放在union的末尾?例如对于工会的每个部分而言不是一个订单。这是我上次写联合sql语句时绊倒了我。 (nb:我上次写的是在oracle中的SQL,我不知道postgresql或mysql中的行为是否不同) –
@OleHenrikSkogstrømyep。根据SQL标准,ORDER BY子句必须放在所有联合之后。但阿雷尔不能这样做。我建议分割SQL和ORDER BY子句,以便可以使用不同顺序的一个SQL。 –
你是正确的Rails不支持has_many:通过w /多态关联。你可以通过在你的User类上定义一个实例方法来模仿这种行为。这看起来像这样:
def articles
Article.
joins("join subscriptions on subscriptions.target_id = articles.id and subscriptions.target_type = 'Article'").
joins("join users on users.id = subscriptions.user_id")
end
所以,你基本上想要一个给定的用户订阅的所有文章? – nicooga
是的,就是这样。 – atomAltera
没有标准的解决方案,只需使用ActiveRecord dsl。我的解决方案将以与您的关系相同的方式工作,请参阅第二次编辑。 – nicooga