Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use joins only if condition is met

I would like to make a joins query but only if a condition is met.

In previous version of rails when find was used, I would be able to use:

options = { :order=> 'courses.name asc',
:include => [:units],
:group => 'courses.name',
:conditions => conditions }

options[:join] = :course_sub_responsibles if YOUR CONDITION GOES HERE

@courses = Course.find(:all, options)

But in current version, how can I do that?

See here: Rails - use join only if a condition is true

But the second answer will not work for me, because I can not build the query piece by piece. Doing so will cause the first query to fetch a huge amount of data.

like image 311
Noam B. Avatar asked Sep 21 '25 09:09

Noam B.


1 Answers

I believe you can do something like:

query = Course.where(<your conditions>).order(<your order>)
query = query.joins(<your joins>) if YOUR CONDITION GOES HERE
@courses = query

Rails won't query the database until you use something like to_a / each / pluck.

To test this in the console you can do something like (borrowing from @3limin4t0r's comment):

foo = Course.all; nil

At this point no SQL should have been run. If you then do foo on the console you'll see it run the query - the console will print out the result and this will trigger rails to grab the data for it.

like image 188
Ben Stephens Avatar answered Sep 23 '25 02:09

Ben Stephens