views:

51

answers:

2

Hi, while writing some application for personal use. I find out the child query is not as great as it look.

For instance, I have 2 object

Category has_many Files
File belongs_to Category

File.category will access its parent category. But this lead to the famous N+1 problem.

For example, I want my homepage to list out 20 newest files and its corresponding category using something like this

for file in @files
  %p
    = file.name
    = file.category.name

How should I solve this problem?

+2  A: 

In your find if you say :include => :category then this will eager load the categories for you and avoid a separate query to retrieve each category's name. So for your example of the 20 most recent files you could do:

@files = File.find :all, :limit => 20, :include => :category,
  :order => 'created at desc'
mikej
+6  A: 
@files = File.find(:all, :limit => 20, :order => "created at desc", :include => :category)
mark