Noam B.
Noam B.

Reputation: 3250

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.

Upvotes: 4

Views: 750

Answers (2)

Ben Stephens
Ben Stephens

Reputation: 3371

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.

Upvotes: 5

Lam Phan
Lam Phan

Reputation: 3811

you can create a scope that will check the condition before joins

class Course
 scope :joins_if, -> (table, cond) {
  joins(table) if cond
 } 
end

then

Course.where...joins_if(:course_sub_responsibles, YOUR CONDITION GOES HERE)

Upvotes: 1

Related Questions