Amree
Amree

Reputation: 2890

Understainding Rails queries in loops

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 >     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?

Upvotes: 0

Views: 636

Answers (1)

Ben Lee
Ben Lee

Reputation: 53319

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

Upvotes: 2

Related Questions