Ruby on Rails 3 howto make 'OR' condition

2019-01-11 02:10发布

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?

9条回答
放荡不羁爱自由
2楼-- · 2019-01-11 03:06

You can define an Array as value in the :conditions Hash.

So you could do for example:

Account.all(:conditions => { :id => [1, 2] })

Tested with Rails 3.1.0

查看更多
来,给爷笑一个
3楼-- · 2019-01-11 03:07

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
查看更多
smile是对你的礼貌
4楼-- · 2019-01-11 03:12

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

Account.where(["id in (?)", [1, 2]])
查看更多
登录 后发表回答