Nick ONeill
Nick ONeill

Reputation: 7379

Is there any way to avoid excess ActiveRecord calls?

I have the following ActiveRecord call in a Rails controller ("filings#index"):

@filings = Filing.order("created_at DESC").limit(limit).offset(start).joins("LEFT OUTER JOIN companies ON companies.id=filings.company_id")

Each Filing belongs_to a Company. I would like to be able to access:

@filings.first.company

Without having to make an additional SQL query as that was the entire purpose of completing an OUTER JOIN in the first place. However when I call @filings.first.company it performs an additional query:

SELECT "companies".* FROM "companies" WHERE "companies"."id" = 989 LIMIT 1

How can I avoid this second query from taking place? Shouldn't the information already have been stored as a result of the initial query?

Upvotes: 1

Views: 85

Answers (1)

Jason Noble
Jason Noble

Reputation: 3766

You need to include the information from the database:

@filings = Filing.includes(:company).order("created_at DESC").offset(start).limit(limit)

hat tip to John Naegle and tharrison

Upvotes: 1

Related Questions