Rails named_scope output in log files

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.

This entry was posted on Sun, 09 Nov 2008 05:59:00 GMT . You can follow any any response to this entry through the Atom feed. You can leave a comment .


Comments

Leave a response

  1. François Beausoleil 1 day later:

    If you call #all at the end of your association chain, this will load the collection immediately. Same as if you called #find(:all). That way, the load will happen before rendering.

  2. Tom 19 days later:

    It turns out that this behavior can be a feature. When using fragment caching, one of the problem areas is having to check in the controller to see if the fragment is cached and also checking in the View code.

    If the controller code never actually runs the query, then this checking never needs to be done. It feels strange, but it makes the controller code a lot cleaner to look at, as the controller never needs to know how the View gets built.

Leave a comment