Katie M
Katie M

Reputation: 1131

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.

Upvotes: 6

Views: 23004

Answers (3)

AWM
AWM

Reputation: 1140

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.

Upvotes: 11

exbinary
exbinary

Reputation: 1086

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

Upvotes: 8

Hare Kumar
Hare Kumar

Reputation: 719

Well

First get all the state_id & store it in array. and then pass that array in where clause. It is similar to Mysql IN query.

Hence your query will be something like:

state_id = [1, 2, 3]  
Request.pending.where(:state_id => state_id AND :approved_id => current_user.id)

I hope it will fetch you the desired result.

Upvotes: 1

Related Questions