Rails,范围,OR和连接

时间:2011-02-18 22:01:00

标签: ruby-on-rails activerecord scope

我有一个范围:

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似乎失败了:

它不会呈现仅具有适当扇区但没有相关建议的配置文件。想法?

3 个答案:

答案 0 :(得分:10)

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

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

这还包括没有建议的配置文件。

答案 1 :(得分:8)

您可以通过在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更加健壮。

答案 2 :(得分:3)

查看http://metautonomo.us/projects/metawhere/以获得更多查询优势......

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

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