Rails named_scope output in log files

November 8, 2008 Link to post  Permalink

I’ve been using the new Rails feature of named_scope for my current project. One thing I do for all new pages is to check the Rails development.log file to make sure that the SQL queries I’m expecting are actually the ones that are executed.

Typically, my controller will run the queries to get all the data, and the views will use the results to display the data. This pattern is clear in the log file. The Controller runs the query and retrieves the data before the View code is executed.

However, named_scope queries don’t actually perform the database query until the data is actually requested in the code, so the SQL text in the log file will show up when the views are rendering, not when the controller code runs. And if the view never uses the results, the query is never executed.

All of this is transparent to your code, but it caused me a few minutes of confusion trying to find the query that I was expecting to see.