OR and Ruby where clause statements

Probably very easy, but it’s hard for them to find documentation online about this. I have two activerecord queries in Ruby that I want to combine with the OR operator

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

im new for ruby, but tried this on my own using ||

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

this did not work, therefore 1. id would like to know how to actually do it in Ruby and 2. if this person can also give me a head-up in boolean syntax in a ruby ​​statement like this in general. e.g. AND, OR, exclusive OR ...

+4
source share
3 answers

You cannot use the Hash syntax in this case.

 Project.where("manager_user_id = ? OR account_manager = ?", current_user.id, current_user.id) 
+9
source

You should also review the API documentation and abide by the rules. In this case, for the code you can 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 assume that the value of current_user id comes from your own application, and not from an external source, such as form submissions. If you use the form data that you intend to use in your queries, you must use placeholders so that Rails creates properly shielded 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 a few parameters to the where method (an example with placeholders), the first parameter will be processed by Rails as a template for SQL. The remaining elements in the array will be replaced at run time by the number of placeholders (?) That you use in the first element, which is the template.

+2
source

Metawhere can perform OR operations, as well as many other great things.

+1
source

All Articles