【问题标题】:retrieve reverse multiple records of rails association检索rails关联的反向多条记录
【发布时间】:2014-10-07 03:34:48
【问题描述】:

我有两个模型产品和类别。

我能够成功查询 Category.products 等。

Product.rb

belongs_to :category

Category.rb

has_many :products

现在我只想检索至少包含一种现有产品的类别。

我试过这样:

 @categories = Category.where(Category.products.present?) 

#返回错误未定义方法`products'也更改为product没用。

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    得到您需要带有产品的类别以及产品属性 with_operator 为 true 的评论后,您可以使用 joinsmerge 以“rails 样式”执行该查询:

    @categories = Category.joins(:products).merge(Product.where(with_operator: true)).uniq
    

    这将生成以下 SQL:

    SELECT DISTINCT "categories".* FROM "categories" INNER JOIN "products" ON "products"."category_id" = "categories"."id" WHERE "products"."with_operator" = 't'
    

    您还可以使用 rails 4 语法,正如 @yukke 所指出的:

    Category.joins(:products).where(products: { with_operator: true }).uniq
    

    【讨论】:

    • Rails 合并不会生成 SQL UNION 运算符。您的代码等于下一个: Category.joins(:products).where(with_operator: true).uniq
    • 并不是合并的意图(阅读文档)。合并是为了告诉 rails with_operator 是 products 表的条件,而不是 categories 表的条件。
    • 如果你运行Category.joins(:products).where(with_operator: true).uniq会返回一个错误,因为rails会认为with_operator是分类表的一个属性
    • @rockskull,好的。那么最好使用 rails 4 语法: Category.joins(:products).where(products: { with_operator: true }).uniq
    【解决方案2】:

    您所需要的只是内部连接。它将跳过那些没有产品的类别。要在连接表上添加条件,您可以使用 rails 4 where's 语法:

    @categories = Category.joins(:products).where(products: { with_operator: true }).uniq
    

    它将产生下一个sql查询:

    SELECT DISTINCT "categories".*
    FROM "categories" INNER JOIN "products" ON "products"."category_id" = "categories"."id"
    WHERE "products"."with_operator" = 't'
    

    【讨论】:

    • 他为什么需要to_a?
    • to_a 显式运行 sql 查询并将 ActiveRecord::Relation 转换为 Array。他当然可以跳过,这是一种很好的做法,也是我的习惯。
    • @yukke 现在我面临向@categories = Category.joins(:products).uniq.to_a 添加第二个条件的问题,我如何才能仅检索那些具有with_operator: true 的类别产品?
    • 您需要产品类别或类别 where(with_operator: true) ?
    • 我需要产品类别和product.where(with_operator:true)
    猜你喜欢
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多