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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With