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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With