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?
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.
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.
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.
Account.where(id: [1,2])
no explanation needed.
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With