【问题标题】:Rewrite acrive record query重写活动记录查询
【发布时间】:2022-01-27 17:24:40
【问题描述】:

我有模型Issuehas_many :comments,模型Commenthas_many :assets, as: :assetable, class_name: 'Comment::Asset',和模型Assetbelongs_to :assetable, polymorphic: true

我需要获取特定问题的所有资产。 我的第一个实现如下:

comments = Comment.where(issue_id: issue.id).ids
assets = Asset.where(assetable_id: comments)

然而,它显然远非完美。我相信,这应该用joins 或类似的东西重写,但我没能解决它并找到解决方案。你会推荐什么?

【问题讨论】:

    标签: sql ruby-on-rails ruby join activerecord


    【解决方案1】:

    您可以“手动”使用 cmets 加入 assets 表,因为您不能急切地加载它们之间的多态关联:

    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 = ?
    )
    

    【讨论】:

    • 非常感谢!现在我明白了!
    • 由于Asset 是多态的,仅assetable_id 不足以创建关系,您还需要为assetable_type 列添加条件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 2013-02-01
    • 2013-04-23
    • 2016-11-10
    相关资源
    最近更新 更多