【问题标题】:Rails, scope, OR and joinsRails、范围、OR 和连接
【发布时间】:2011-06-30 03:27:19
【问题描述】:

我有一个范围:

includes(:countries).where("profiles.sector = :sector OR advices.sector = :sector", :sector => sector)

它产生以下 SQL:

SELECT `profiles`.* FROM `profiles` INNER JOIN `advices` ON `advices`.`profile_id` = `profiles`.`id` WHERE (profiles.sector = 'Forestry_paper' OR advices.sector = 'Forestry_paper')

(是的,我的 ProfileCountry 模型中有国家/地区)

不幸的是,OR 似乎失败了:

它不会呈现只有正确部门但没有相关建议的配置文件。想法?

【问题讨论】:

    标签: ruby-on-rails activerecord scope


    【解决方案1】:

    查看http://metautonomo.us/projects/metawhere/ 了解更多查询优势...

    meta_where 现在未维护:https://github.com/activerecord-hackery/meta_where

    Rails 5 引入了 OR 语句: Rails 5: ActiveRecord OR query

    【讨论】:

    • 稍微更新了答案。
    【解决方案2】:

    您可以通过在 includes 之后指定带有哈希的 where 子句来进行外连接:

    Post.includes(:comments).where(:comments=>{:user_id=>nil})
    

    产生:

      Post Load (0.5ms)  SELECT "posts"."id" AS t0_r0, "posts"."created_at" AS t0_r1,
       "posts"."updated_at" AS t0_r2, "comments"."id" AS t1_r0, "comments"."user_id" 
       AS t1_r1, "comments"."post_id" AS t1_r2, "comments"."content" AS t1_r3,
       "comments"."created_at" AS t1_r4, "comments"."updated_at" AS t1_r5 
       FROM "posts" LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id" 
       WHERE ("comments"."user_id" IS NULL)
    

    Ryan Bigg 写了一个helpful blog post about this

    编辑

    请注意,这种技术或多或少是 Rails 为预先加载关联构建 SQL 的方式的副作用。正如接受的答案中所建议的那样,显式 LEFT JOIN 更健壮。

    【讨论】:

      【解决方案3】:

      您正在执行 INNER JOIN,因此它要求配置文件具有相应的建议。请尝试以下方法:

      Profile
        .joins("LEFT JOIN advices ON advices.profile_id = profiles.id")
        .where("profiles.sector = :sector OR advices.sector = :sector", :sector => sector)
      

      这也将包括没有建议的个人资料。

      【讨论】:

      • 谢谢 :) 没有更好的 Rails 编写方式吗?此外,如何使用 LEFT JOIN 链接连接?
      • 没关系,一个简单的AND就完美了
      • 没有其他 Rails 方法可以编写连接。 joins 方法仅适用于内部连接 ​​(guides.rubyonrails.org/…)
      • 您可以随时添加额外的连接调用:joins(...).joins(...) 并且您可以将条件与 AND 或 OR 结合起来:“LEFT JOIN 建议 ON ... AND .. . 和 ...
      • >> 没有其他 Rails 方法可以编写连接
      猜你喜欢
      • 2016-04-14
      • 2016-04-29
      • 2017-06-09
      • 2015-10-20
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      相关资源
      最近更新 更多