views:

125

answers:

3

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?

A: 

I'd go with the IN clause, e.g:

Account.where(["id in ?", [1, 2]])
jpemberthy
That would be appropriate, but notice the author is looking @ 2 different fields...
Brian
Oh yes that's true, I wrote the answer based in this statement `Account.where(:id => 1).or.where(:id => 2)`. Obviously It doesn't work for different fields.
jpemberthy
A: 

I haven't worked w/ Arel much yet, but the following looks like it should work:

Account.where(:payer_id.eq(1).or(:payee_id.eq(2)))

Untested...

Brian
as far as I know, Arel doesn't support yet the 'or' method...
apeacox
I'll have to give it a spin to test then... My answer is based on looking @ the source code for Arel predicates: http://github.com/rails/arel/blob/master/lib/arel/algebra/predicates.rb
Brian
A: 

Sadly, the .or isn't implemented yet (but when it is, it'll be AWESOME).

So you'll have to do something like:

class Project < ActiveRecord::Base
  scope :sufficient_data, :conditions=>['ratio_story_completion != 0 OR ratio_differential != 0']
  scope :profitable, :conditions=>['profit > 0']

That way you can still be awesome and do:

Project.sufficient_data.profitable
Jesse Wolgamott
from the arel github site: The OR operator is not yet supported. It will work like this: users.where(users[:name].eq('bob').or(users[:age].lt(25)))
hjuskewycz