Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails 3 howto make 'OR' condition

I need an SQL statement that check if one condition is satisfied:

SELECT * FROM my_table WHERE my_table.x=1 OR my_table.y=1 

I want to do this the 'Rails 3' way. I was looking for something like:

Account.where(:id => 1).or.where(:id => 2) 

I know that I can always fallback to sql or a conditions string. However, in my experience this often leads to chaos when combining scopes. What is the best way to do this?

Another related question, is how can describe relationship that depends on an OR condition. The only way I found:

has_many :my_thing, :class_name => "MyTable",  :finder_sql => 'SELECT my_tables.* ' + 'FROM my_tables ' + 'WHERE my_tables.payer_id = #{id} OR my_tables.payee_id = #{id}' 

However, these again breaks when used in combinations. IS there a better way to specify this?

like image 450
hjuskewycz Avatar asked Jul 20 '10 14:07

hjuskewycz


People also ask

What is eager loading rails?

Eager loading solves this problem by creating a left outer join on the table, returning all of the data in a single query. Adding an eager load is as simple as adding an :includes statement to the controller.

How do you write if condition in Ruby on Rails?

Ruby if...else Statement Notice Ruby uses elsif, not else if nor elif. Executes code if the conditional is true. If the conditional is not true, code specified in the else clause is executed. An if expression's conditional is separated from code by the reserved word then, a newline, or a semicolon.

What are active records in Rails?

1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


2 Answers

Account.where(id: [1,2]) no explanation needed.

like image 197
Mike Campbell Avatar answered Oct 02 '22 14:10

Mike Campbell


This will works in Rails 5, see rails master :

Post.where('id = 1').or(Post.where('id = 2')) # => SELECT * FROM posts WHERE (id = 1) OR (id = 2) 

For Rails 3.0.4+:

accounts = Account.arel_table Account.where(accounts[:id].eq(1).or(accounts[:id].eq(2))) 
like image 42
weston Avatar answered Oct 02 '22 13:10

weston