2

I am trying to write logic for a search query. There are many different conditions with different parameters. One parameter sent from form is code. So there are code values in two different tables: competitions and responses. What I need is to check the params[:code] value first in competitions table and if it does not exist then check in responses table. If it does not exist in either table then it should return nil. I am trying to write it in a single if statement. The code I tried is below:

competitions = Competition.includes(:event, :responses)
if params[:code].present?
  competitions = (competitions.where(code: params[:code])) || 
  (competitions.joins(:responses).where(responses: { code: params[:code] }))

The above code checks only the value of competitions.where(code: params[:code]). If that value is [], then it is not evaluating the second condition. What changes should I do to make the above code work as per the requirements mentioned above?

0

1 Answer 1

5

competitions.where(code: params[:code]) returns a Relation object which is always truthy.

Luckily enough, it implements #presence method, returning either the value if it’s not blank, or nil. So, this should work:

competitions.where(code: params[:code]).presence || ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.