Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 Syntax - Multiple Conditions

How would I write this correctly?

Request.pending.where(.....)  ## Request.pending = request.state_id in (1..3)

where these are the conditions:

approver1_id = current_user and state_id = 1
or
approver2_id = current_user and state_id = 2
or
approver3_id = current_user and state_id = 3

It would be really nice if I could put these conditions in the model for use in other controllers/views, too, because I will use these conditions quite often throughout the app.

like image 781
Katie M Avatar asked Oct 28 '13 15:10

Katie M


2 Answers

Try:

Request.pending.where(
  '(approver1_id= ? AND state_id= ?) OR
   (approver2_id= ? AND state_id= ?) OR
   (approver3_id= ? AND state_id= ?)',
  current_user.id,
  1,
  current_user.id,
  2,
  current_user.id,
  3
)

Edit: I forgot that you should use colons. And shouldn't it be 'current_user.id'? It is also unclear whether your Request use the three parameters approver1_id - approver3_id or just one approver_id per request.

Edit 2: Changed query to SQL.

like image 125
AWM Avatar answered Sep 27 '22 23:09

AWM


To answer the second part of your question about reusing this query, you can just define a class method on Request that accepts a user parameter:

# usage: Request.pending_approval(current_user)
def self.pending_approval(user)
  pending.where("(approver1_id = :user AND state_id = 1) OR 
                 (approver2_id = :user AND state_id = 2) OR 
                 (approver3_id = :user AND state_id = 3)", 
                user: user)
end

If you want to be able to reuse the individual fragments of the query and combine them as needed, see this related answer (Note, the answer linked to is better than the accepted one, IMO).

like image 33
exbinary Avatar answered Sep 28 '22 00:09

exbinary