Tintin81
Tintin81

Reputation: 10207

How to reduce number of SQL queries in Ruby on Rails 3 when fetching associated records

I am new to Ruby on Rails and I have two tables Projects and Tasks.

In my Tasks index view I have a long HTML table with one column belongs to Project.

Now I noticed that Rails uses a separate SQL query to fetch the name of each Project.

Is there any way to streamline this? I think I've heard of some technique a while ago but can't quite remember what it was.

Thanks for any help!

Upvotes: 1

Views: 363

Answers (1)

fullsailor
fullsailor

Reputation: 886

Use the includes method on your initial Task query.

Example:

def index
  @tasks = Task.includes(:project).all
  ...
end

Upvotes: 10

Related Questions