hjuskewycz hjuskewycz - 2 years ago 71
Ruby Question

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?

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download