Rails 4 Syntax - Multiple Conditions

How can I write this correctly?

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

where are these 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 very nice if I could put these conditions in the model for use in other controllers / views, because I will use these conditions quite often throughout the application.

+6
source share
3 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 should not be "current_user.id"? It is also unclear whether your request uses the three approver1_id parameters - approver3_id or only one approver_id argument for each request.

Edit 2: Changed SQL query.

+11
source

To answer the second part of the question about reusing this request, you can simply 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 individual request fragments and combine them as necessary, see this related answer (note that the answer associated with it is better than accepted, IMO).

+7
source

Good

First get all state_id and save it in an array. and then pass this array to where where. It looks like a Mysql IN query.

Therefore, your query will look something like this:

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

I hope that it will bring you the desired result.

+1
source

Source: https://habr.com/ru/post/956882/


All Articles