理解循环中的Rails查询

时间:2011-09-28 07:24:41

标签: mysql activerecord ruby-on-rails-3.1

我可以使用一些帮助来理解循环中的Rails查询。

循环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 

循环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 

循环3:

ruby-1.9.2-p290 :011 > (1..3).each do |i|
ruby-1.9.2-p290 :012 >     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

为什么没有第二个循环运行?

1 个答案:

答案 0 :(得分:2)

Unit.where("id = ?", i)实际上并未运行查询,只是设置ActiveRecord::Relation。所以就它本身而言,它只是评估一个表达式。要实际运行查询,您可以这样做:

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