简体   繁体   中英

How to find records with 2 not condition in rails where clause?

I have a users table like this:

--------------------
| id | name | role |
--------------------
| ...| ...  | ...  |
--------------------

The role column has 3 kinds of role: Admin, Buyer, and User. With convention below:

role != 'buyer' and role != 'admin' ==> User is a normal user

( This means role can have value: nil, "", or manny different values, except 'buyer' and 'admin' )

role = 'buyer' ==> User is a buyer

role = 'admin' ==> User is an admin

Now, I want to find all the users in all 3 scenarios:

@admins = User.where(role: 'admin').all (work fine!)
@buyers = User.where(role: 'buyer').all (work fine!)

And all normal users, but this seems not working:

@users = User.where("role!='buyer' and role!='admin'").all (not working! )

Can anyone help me find all the normal users? Thanks in advance!

For all rails version,

User.where('role NOT IN (?)', ['buyer', 'admin'])

If you are using rails >= 4,

User.where.not(role: ['buyer', 'admin'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM