Chitrank Samaiya
Chitrank Samaiya

Reputation: 841

How to use joins inside includes in rails active record query?

I am just trying to improve query, so that it result's in improving performance fo application.

 Student.includes(:parents =>:emails).where("emails.email_address is not null and emails.email_address != ''")

I just wanted to meet conditions using emails table, so clearly it is not required to eagerload emails table, instead i would prefer joins. But I am not able to figure out, how to use includes and joins together?. So that it should eagerload parents and joins with emails

Upvotes: 8

Views: 9897

Answers (1)

Kkulikovskis
Kkulikovskis

Reputation: 2088

you do this by chaining both together:

Student.joins(parents: :emails).includes(:parents).where("emails.email_address is not null and emails.email_address != ''")

The way it works is that joins will create a JOIN but not kep any of the data in memory, whereas includes will preload the data in memory but not create the join.

I suggest reading this blog post: https://web.archive.org/web/20200804112405/http://tomdallimore.com/blog/includes-vs-joins-in-rails-when-and-where/

Upvotes: 18

Related Questions