How to properly add brackets to SQL queries with 'or' and 'and' clauses by using Arel?

后端 未结 3 2072
遥遥无期
遥遥无期 2021-01-05 06:33

I am using Ruby on Rails 3.2.2 and I would like to generate the following SQL query:

SELECT `articles`.* FROM `articles` WHERE (`articles`.`user_id` = 1 OR `         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-05 07:16

    I've successfully used this gem: squeel which comes on top of Arel so you don't have to mess with it. So in order to generate your query you would do something like this in Squeel:

    @articles = Article.
      where{
      ( user_id.eq(1) | status.eq('published') ) |
      ( user_id.in([10, 11, 12, '<...>']) & status.eq('temp') )
    }
    
    # since this is an ActiveRecord::Relation we can play around with it
    @articles = @articles.select{ [ user_id, status ] }
    
    # and you can also inspect your SQL to see what is going to come out
    puts @articles.to_sql
    

    The more complicated your queries get the more you're going to like this gem.

提交回复
热议问题