Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails .where(.... and ....) Searching for two values of the same attribute

I've tried

@users = User.where(name: @request.requester or @request.regional_sales_mgr)

and

@users = User.where(name: @request.requester).where(name: @request.regional_sales_mgr).all

This doesn't seem to work. What I want is to find the user whose name matches @request.requester, and the user whose name matches @request.regional_sales_mgr, and save them both into the variable @users.

like image 916
sabrams Avatar asked Nov 25 '13 16:11

sabrams


2 Answers

In the general case "OR" queries can be written as:

User.where("users.name = ? OR users.name = ?", request.requester, request.regional_sales_mgr)

Note: Rails 5 will support OR using:

User.where(name: request.requester).or(User.where(name: request.regional_sales_mgr))

For this specific case as state in other answers an IN query is simpler:

User.where(name: [request.requester, request.regional_sales_mgr])
like image 150
Kevin Sylvestre Avatar answered Oct 08 '22 14:10

Kevin Sylvestre


You want to use the SQL IN clause. Activerecord provides a shortcut to this:

@users = User.where(name: [@request.requester, @request.regional_sales_mgr]).all

Giving an array of values to name: will generate the following SQL statement:

SELECT * FROM users WHERE name IN (value1, value2, and so on...);

This should find all the users whose names are @request.requester or @request.regional_sales_mgr

like image 28
DiegoSalazar Avatar answered Oct 08 '22 13:10

DiegoSalazar