ruby / rails范围内的原始SQL

时间:2014-09-05 09:42:15

标签: sql ruby-on-rails ruby rails-activerecord

我想了解以下两个版本的rails scope之间的区别。我相信他们的功能是一样的。但是,在使用它们时,我确实观察到生成的SQL有很多不同。


版本1(RAW SQL)

scope :ignore_unavailable, lambda { 
  where(["Item.id not in (select id from Cars where Cars.status = 'NA'"])
}


第2版

scope :ignore_unavailable, lambda { 
ids = Cars.select("id").where("status = 'NA'");
idsStr = ''
idsarr = ids.collect{|car| car.id}.flatten
where(["Item.id not in (" + idsarr.join(",") + ")"])
}

在我看来,版本2生成的优化查询比版本1更多,但我不明白为什么会这样。 谁能解释一下这里会发生什么?

0 个答案:

没有答案