Rails,范围,OR和连接

apn*_*ing 3 activerecord scope ruby-on-rails

我有一个范围:

includes(:countries).where("profiles.sector = :sector OR advices.sector = :sector", :sector => sector)
Run Code Online (Sandbox Code Playgroud)

它产生以下SQL:

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

(是的,我Profile和我的Country模特中都有国家)

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

它不会使配置文件只有适当的扇区,但没有相关的建议.思考?

Pan*_*kos 10

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

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

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


zet*_*tic 8

您可以通过在以下位置之后使用哈希指定where子句来执行外连接includes:

Post.includes(:comments).where(:comments=>{:user_id=>nil})
Run Code Online (Sandbox Code Playgroud)

生产:

  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)
Run Code Online (Sandbox Code Playgroud)

Ryan Bigg写了一篇有用的博客文章.

编辑

请注意,此技术或多或少是Rails为急切加载关联构造SQL的方式的副作用.如公认的答案所示,显式LEFT JOIN更加健壮.