Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 471
Chitrank Samaiya Avatar asked Jun 06 '16 06:06

Chitrank Samaiya


1 Answers

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/

like image 79
Kkulikovskis Avatar answered Oct 07 '22 12:10

Kkulikovskis