Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy loading in Rails 3.2.6

I have found in several resources online than when doing stuff like:

cars = Car.where(:colour => 'black')

The query is not executed, until you do something like:

cars.each {|c| puts c.name } 

However, in my Rails 3.2.6 project, when I do the following in the console:

User.where(:first_name => "John")

I get the following:

 User Load (1.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`first_name` = 'John'

So, the query is being executed right?

Where did the lazy loading go? Or am I missing something here?

like image 304
Hommer Smith Avatar asked Jul 28 '12 15:07

Hommer Smith


Video Answer


1 Answers

The console calls inspect on the result of any expression you type so that it can display it to you. inspect is one of the things that will trigger the load of the query. If you instead do

x = User.where(:first_name => 'John'); false

then you should see no query because this time the console is calling inspect on false instead of on the Active Record relation object.

like image 195
Frederick Cheung Avatar answered Sep 24 '22 16:09

Frederick Cheung