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 02:46

With rails_or, you could do it like:

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

(It works in Rails 4 and 5, too.)

查看更多
beautiful°
3楼-- · 2019-01-11 02:47

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)))
查看更多
戒情不戒烟
4楼-- · 2019-01-11 02:50

Alternate syntax using Hash

Account.where("id = :val1 OR id = :val2", val1: 1, val2: 2).

This is particularly useful, when the value is compared with multiple columns. eg:

User.where("first_name = :name OR last_name = :name", name: 'tom')
查看更多
小情绪 Triste *
5楼-- · 2019-01-11 02:53

I've used the Squeel gem (https://github.com/ernie/squeel/) to do OR queries and it works beautifully.

It lets you write your query as Account.where{(id == 1) | (id == 2)}

查看更多
乱世女痞
6楼-- · 2019-01-11 03:00

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

查看更多
狗以群分
7楼-- · 2019-01-11 03:01

Those arel queries are unreadable to me.

What's wrong with a SQL string? In fact, the Rails guides exposes this way as the first way to make conditions in queries: http://guides.rubyonrails.org/active_record_querying.html#array-conditions

So, I bet for this way to do it as the "Rails way":

Account.where("id = 1 OR id = 2")

In my humble opinion, it's shorter and clearer.

查看更多
登录 后发表回答