0

I have this users:

NAME _____ ROLE_________STATUS

user1 -------- role1 ---------------- true

user2 -------- role2 ---------------- true

user3 -------- role2 ---------------- false

user4 -------- role3 ---------------- false

user5 -------- role4 ---------------- true

I have this query:

User.where("role = ? OR role = ? OR role = ? AND status = ?", "role1", "role2", "role3", true)

and i expect that the data will be retrieve is:

user1

user2

but the system retrieve the user3 even if his status is false.

I also try to change AND to OR but it retrieves all.

what's wrong about my query?

3 Answers 3

2

What's wrong with the query is the lack of parentheses around the 'OR groups'

User.where("(role = ? OR role = ? OR role = ?) AND status = ?", "role1", "role2", "role3", true)

However, as already stated in another answer, it can be done in an easier way like this.

User.where(status: true).where(role: %w{role1 role2 role3})
Sign up to request clarification or add additional context in comments.

Comments

1

try this :

User.where(status: true).where(role: ["role1", "role2", "role3"])

Comments

1

Try using parentheses to group the conditions:

User.where("(role = ? OR role = ? OR role = ?) AND status = ?", "role1", "role2", "role3", true)

The tricky bit might be the true, is it just stored as a string? e.g. a varchar or text column?

As an alternative, you can also use the IN operator

User.where("role IN (?, ?, ?) AND status = ?", "role1", "role2", "role3", true)

1 Comment

User.where("role IN (?, ?, ?) AND status = ?", "role1", "role2", "role3", true) ---> works in me! Thanks for the answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.