![](/img/trans.png)
[英]ActiveRecord polymorphic has_many with ActiveSupport::Concern
[英]ActiveRecord has_many through polymorphic has_many
看起來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))
我需要根據用戶#訂閱通過Subscription#target#article選擇文章。
我不知道如何實現這一點
理想情況下,我想獲得Association類的實例
更新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
我在User模型中按類型分隔文章來源:
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
(這僅適用於用戶和類別)
它支持范圍和其他功能。 唯一讓我感興趣的是:這個查詢會導致一些不良影響嗎?
我認為從DB性能前瞻性使用UNION ALL multiquery將比使用多態multijoin更有效。 它也會更具可讀性。 我嘗試編寫一個Arel查詢作為示例,但它不能很好(我沒有使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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.