Does Rails 4 have support for OR queries

前端 未结 7 1917
暗喜
暗喜 2020-12-08 13:14

So in Rails 4 the long desired feature to use not queries has been added.

Article.where.not(title: \'Rails 3\')

Has similar su

相关标签:
7条回答
  • 2020-12-08 13:35

    You can use Squeel for more complex queries:

    Article.where{(title == 'Rails 3') | (title == 'Rails 4')}
    

    This results in the following SQL query:

    SELECT `articles`.* FROM `articles` WHERE ((`articles`.`title` = 'Rails 3' OR `articles`.`title` = 'Rails 4'))
    
    0 讨论(0)
  • 2020-12-08 13:36
    Article.where(title: ['Rails 3', 'Rails 4'])
    

    is how you'd do that in Active Record.

    It's not possible to replicate any arbitrary SQL query using "Rails-y" syntax. But you can always just pass in literal sql.

    So you could also do:

    Article.where("articles.title = 'Rails 3' OR articles.title = 'Rails 4'")
    
    0 讨论(0)
  • 2020-12-08 13:38

    This now works in Rails 5:

    Article.where(title: 'Rails 3').or(Article.where(title: 'Rails 4'))
    

    Code example in Rails's source.

    0 讨论(0)
  • 2020-12-08 13:47

    The most common alternative is already answer by @gregates

    Recently there has been pull request in rails source

    Add #any_of query method to active_record Which adds or functionality to activerecord

    the contributor has already created a gem incase its not accepted

    its rails 3.2 and 4 compatible

    https://github.com/oelmekki/activerecord_any_of

    I havent tried it yet but soon wish to use it looks good to me.

    0 讨论(0)
  • 2020-12-08 13:47

    I know that this is an old thread, but anyone else looking for a solution to this problem might find this code helpful:

    Article.where(title: ["Rails 3", "Rails 4"])
    

    Maybe that will help you get someone going in the right direction without having to risk sql injection.

    0 讨论(0)
  • 2020-12-08 13:47

    It seems that the rails master branch is now supporting OR queries. https://github.com/rails/rails/pull/16052

    I assume it will be in the framework with the next major release.

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