Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OR operators and Ruby where clause

Probably really easy but im having trouble finding documentation online about this I have two activerecord queries in Ruby that i want to join together via an OR operator

@pro = Project.where(:manager_user_id => current_user.id )
@proa = Project.where(:account_manager => current_user.id)

im new to ruby but tried this myself using ||

@pro = Project.where(:manager_user_id => current_user.id || :account_manager => current_user.id)

this didnt work, So 1. id like to know how to actually do this in Ruby and 2. if that person can also give me a heads up on the boolean syntax in a ruby statement like this altogether. e.g. AND,OR,XOR...

like image 857
SD1990 Avatar asked Sep 21 '11 13:09

SD1990


2 Answers

You can't use the Hash syntax in this case.

Project.where("manager_user_id = ? OR account_manager = ?", current_user.id, current_user.id)
like image 176
Simone Carletti Avatar answered Sep 22 '22 11:09

Simone Carletti


You should take a look at the API documentation and follow conventions, too. In this case for the code that you might send to the where method.

This should work:

@projects = Project.where("manager_user_id = '#{current_user.id}' or account_manager_id = '#{current_user.id}'")

This should be safe since I'm assuming current_user's id value comes from your own app and not from an external source such as form submissions. If you are using form submitted data that you intent to use in your queries you should use placeholders so that Rails creates properly escaped SQL.

# with placeholders
@projects = Project.where(["manager_user_id = ? or account_manager_id = ?", some_value_from_form1, some_value_from_form_2])

When you pass multiple parameters to the where method (the example with placeholders), the first parameter will be treated by Rails as a template for the SQL. The remaining elements in the array will be replaced at runtime by the number of placeholders (?) you use in the first element, which is the template.

like image 29
Andrés N. Robalino Avatar answered Sep 23 '22 11:09

Andrés N. Robalino