我的模型Issue是has_many :comments,模型Comment是has_many :assets, as: :assetable, class_name: 'Comment::Asset'和模型Asset是belongs_to :assetable, polymorphic: true
我需要獲得特定問題的所有資產。我的第一個實作如下:
comments = Comment.where(issue_id: issue.id).ids
assets = Asset.where(assetable_id: comments)
然而,它顯然遠非完美。我相信,這可以使用joins或類似的東西重寫,但我無法解決它并找到解決方案。你會推薦什么?
uj5u.com熱心網友回復:
您可以“手動”加入帶有注釋的資產表,因為您不能急切地加載它們之間的多型關聯:
Asset
.joins('JOIN comments ON comments.id = assets.assetable_id')
.where(comments: { issue_id: issue.id })
但是,如果一個連接是不是真的需要,where再加上select做的伎倆還有:
Asset.where(assetable_id: Comment.where(issue_id: issue.id).select(:id))
請注意,由于select(:id)使用了而不是ids(從結果行中一次提取每個 id),因此只執行了一個查詢:
SELECT assets.*
FROM assets
WHERE assets.assetable_id IN (
SELECT comments.id
FROM comments WHERE
comments.issue_id = ?
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/397723.html
