如何使用Arel使用’或’和’和’子句正确添加括号到SQL查询?

我正在使用 Ruby on Rails 3.2.2,我想生成以下SQL查询
SELECT `articles`.* FROM `articles` WHERE (`articles`.`user_id` = 1 OR `articles`.`status` = 'published' OR (`articles`.`status` = 'temp' AND `articles`.`user_id` IN (10,11,12,<...>)))

通过这种方式使用Arel

Article
 .where(
   arel_table[:user_id].eq(1)
   .or(arel_table[:status].eq("published"))
   .or(
     arel_table[:status].eq("temp")
     .and(
       arel_table[:user_id].in(10,<...>)
     )
  )
)

它会生成以下内容(注意:括号与第一个SQL查询不同):

SELECT `articles`.* FROM `articles` WHERE (((`articles`.`user_id` = 1 OR `articles`.`status` = 'published') OR `articles`.`status` = 'temp' AND `articles`.`user_id` IN (10,<...>)))

由于我认为后一个SQL查询不能作为第一个“工作”,我怎么能使用Arel(或者,可能还有别的东西)来生成SQL查询作为第一个

更新(评论后)

鉴于上面的SQL查询“工作”相同,但我仍然希望生成确切的SQL查询作为问题中的第一个(主要原因是第一个SQL查询比第一个SQL查询更可读一个用得少而且“明确”括号),我怎么能用Arel来做到这一点?

解决方法

我已经成功地使用了这个宝石: squeel在Arel之上,所以你不必乱用它.因此,为了生成您的查询,您可以在squeel中执行以下操作:
@articles = Article.
  where{
  ( user_id.eq(1) | status.eq('published') ) |
  ( user_id.in([10,'<...>']) & 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

您的查询越复杂,您就越喜欢这个宝石.

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 &#39;EastRiver&#39; 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...