Lax_Sam
Lax_Sam

Reputation: 1139

Assign value to a variable using || operator with if condition in Ruby

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?

Upvotes: 2

Views: 1092

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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 || ...

Upvotes: 5

Related Questions