0

Helo,

My query:

@county = County.joins(:state)  
      .where("counties.slug = ? AND states.slug = ?", params[:county_slug])  
      .select('states.*, counties.*')  
      .first!  

From the log, the SQL looks like this:

SELECT states.*, counties.* FROM "counties" INNER JOIN "states" ON "states"."id" = "counties"."state_id"  LIMIT 1

My problem is that is doesn't eager load the data from the associated table (states), because when I do, for example, @county.state.name, it runs another query, although, as you can see from the log, it had already queried the database for the data in that table as well. But it doesn't pre populate @county.state

Any idea how i can get all the data from the database in just ONE query?

Thx

1 Answers1

0

I think you need to use include instead of joins to get the eager loading. There's a good railscasts episode about the differences: http://railscasts.com/episodes/181-include-vs-joins , in particular:

The question we need to ask is “are we using any of the related model’s attributes?” In our case the answer is “yes” as we’re showing the user’s name against each comment. This means that we want to get the users at the same time as we retrieve the comments and so we should be using include here.

ramblex
  • 3,042
  • 21
  • 20