Alexandre Markiewicz Alexandre Markiewicz - 2 months ago 14
SQL Question

Rails models : SQL OR AND keywords

I use rails and i want a request likes that :

SELECT * FROM events WHERE id = 5 AND
active = true AND
(current_state = 0 OR current_state = 1)


I write something likes that :

Event.where(id:5).where(active:true).or(Event.where(current_state:)).or
(Event.where(current_state: 1))


But when i do that, i have this request :

SELECT * FROM events WHERE id = 5 AND
active = true AND
current_state = 0 OR current_state = 1


How can i have parentheses ?

Answer

You can do something like this:

Event.where('WHERE id = ? AND active = ? AND (current_state = ? OR current_state = ?)',5,true,0,1)