ActiveRecord Rails 4.2 - Filter includes request
I am trying to improve some queries in my Rails 4.2 project. One request, in particular, is done in an API controller. The request looks like this (as an example):
@books = Book.includes(:pages).where( category_id: 1 )
This creates the following SQL:
SELECT "books".* FROM "books" WHERE "books".category_id = 1
SELECT "pages".* FROM "pages" WHERE "pages"."book_id" IN (1, 2, 3)
That's good, it behaves just fine on the database side.
Then suppose I need to filter books based on a page attribute. The request will be something like this:
@books = Book.includes(:pages).where( category_id: 1, pages: { attr1: 'bar' } )
This creates the following SQL:
SELECT "books".attr1, "books".attr2, "pages".attr1, "pages".attr2
FROM "books"
LEFT OUTER JOIN "pages" ON "books".id = "pages".book_id
WHERE "books".category_id = 1 AND "pages".attr1 = 'bar';
This isn't necessarily a bad thing. However, I would like to have the following SQL instead:
SELECT "books".* FROM "books" WHERE "books".category_id = 1
SELECT "pages".* FROM "pages" WHERE "pages"."book_id" IN (1, 2, 3) AND "pages".attr1 = 'bar'
You see, it's easier to create indexes for each individual query in the database.
Is there a way that I can achieve what I want?
Thank.
PS: Please excuse any typo in the written code.
+3
source to share
No one has answered this question yet
Check out similar questions: