开发者

Understainding Rails queries in loops

开发者 https://www.devze.com 2023-04-08 18:03 出处:网络
I could use some help understanding Rails queries in loops. Loop 1: ruby-1.9.2-p290 :005 > (1..3).each do |i|

I could use some help understanding Rails queries in loops.

Loop 1:

ruby-1.9.2-p290 :005 > (1..3).each do |i|
ruby-1.9.2-p290 :006 >     Unit.find(i)
ruby-1.9.2-p290 :007?>   end
  Unit Load (0.2ms)  SELECT `units`.* FROM `units` WHERE `units`.`id` = 1 LIMIT 1
  Unit Load (0.1ms)  SELECT `units`.* FROM `units` WHERE `units`.`id` = 2 LIMIT 1
  Unit Load (0.1ms)  SELECT `units`.* FROM `units` WHERE `units`.`id` = 3 LIMIT 1
 => 1..3 

Loop 2:

ruby-1.9.2-p290 :008 > (1..3).each do |i|
ruby-1.9.2-p290 :009 >     Unit.where("id = ?", i)
ruby-1.9.2-p290 :010?>   end
 => 1..3 

Loop 3:

ruby-1.9.2-p290 :011 > (1..3).each do |i|
ruby-1.9.2-p290 :012开发者_JS百科 >     Unit.find(i)
ruby-1.9.2-p290 :013?>   end
  Unit Load (0.2ms)  SELECT `units`.* FROM `units` WHERE `units`.`id` = 1 LIMIT 1
  Unit Load (0.1ms)  SELECT `units`.* FROM `units` WHERE `units`.`id` = 2 LIMIT 1
  Unit Load (0.1ms)  SELECT `units`.* FROM `units` WHERE `units`.`id` = 3 LIMIT 1
 => 1..3

Why didn't the second loop run?


Unit.where("id = ?", i) doesn't actually run a query, it just sets up an ActiveRecord::Relation. So on it's own, it just evaluates to an expression. To actually run the query, you would do this:

Unit.where("id = ?", i).first
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号