Ruby on Rails 3 howto make 'OR' condition

前端 未结 9 1344
無奈伤痛
無奈伤痛 2020-12-03 00:34

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 th

相关标签:
9条回答
  • 2020-12-03 01:01

    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')
    
    0 讨论(0)
  • 2020-12-03 01:11

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

    Account.where(["id in (?)", [1, 2]])
    
    0 讨论(0)
  • 2020-12-03 01:12

    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)))
    
    0 讨论(0)
  • 2020-12-03 01:15

    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)}

    0 讨论(0)
  • 2020-12-03 01:17

    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

    0 讨论(0)
  • 2020-12-03 01:19

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

    0 讨论(0)
提交回复
热议问题