【问题标题】:Nested includes with where on Rails嵌套包含在 Rails 上的位置
【发布时间】:2017-02-14 12:41:04
【问题描述】:

假设我们有 3 个表:

products (title, product_type_id)
product_types (title)
product_type_options (product_type_id, size)

我想加载产品、它的类型和仅特定的 product_type_options (product_type_options.size = 'XL')

是否可以在 Rails 中不进行 N+1 查询?

类似:

Product.includes( product_type: [product_type_options] )
       .where("product_type_options.size = 'XL'")

我无法让它与where 参数一起工作。任何的想法?

【问题讨论】:

    标签: ruby-on-rails rails-activerecord


    【解决方案1】:

    这应该可以工作

    Product.includes(product_type: :product_type_options)
      .where(product_types: { product_type_options: { size: 'XL' } })
    

    【讨论】:

      【解决方案2】:

      @Iceman 很接近...它没有看到“product_types”的原因是因为它需要在 where 子句中表示为显式哈希,然后 Ruby 会进行正确的嵌套...

      Product.includes(product_type: :product_type_options)
        .where({ product_types: { product_type_options: { size: 'XL' } } })
      

      奇怪,但是在 where 子句中添加额外的 {} 会使嵌套包含工作。

      【讨论】:

        【解决方案3】:

        请试试这个,这是一个小的语法变化。我还没有测试过。让我知道它是否有效:)

        Product.includes( product_type: [product_type_options] )
           .where("product_type_options.size" => 'XL')
        

        【讨论】:

        • 答案是问题中的示例。那时没有用。请改进您的答案或考虑将其删除。
        • 我的回答是改进或解决所提出的问题。请查看我所做的更改。任何人都可以从更改中推断出解决他自己版本的类似于这篇文章的问题。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多