Ruby on rails 带有AND和OR的复杂Arel条件

Ruby on rails 带有AND和OR的复杂Arel条件,ruby-on-rails,arel,Ruby On Rails,Arel,我有一个问题,就是关于操作优先级,将几个条件与和和或组合在一起 因此,我需要生成以下SQL字符串以传入where方法: where("NOT ((assignments.to IS NOT NULL AND assignments.to < :start_date) OR assignments.from > :end_date)", start_date: date.at_beginning_of_week, end_date: date.at_end_of_week) 但Are

我有一个问题,就是关于操作优先级,将几个条件与
组合在一起

因此,我需要生成以下SQL字符串以传入
where
方法:

where("NOT ((assignments.to IS NOT NULL AND assignments.to < :start_date) OR assignments.from > :end_date)", start_date: date.at_beginning_of_week, end_date: date.at_end_of_week)
但Arel并没有用括号括住带有
的条件,因此该条件选择了错误的数据。如何在这种情况下放置括号?

您可以尝试:

table[:from].lt(end_date).and(
  table[:to].eq(nil).or(table[:to].gt(start_date))
)

也许我遗漏了一些东西,但无论如何,你应该避免在sql中使用
NOT
,或者在ruby中使用
除非使用
,因为这不是一个好的实践

你可以使用
table.grouping
方法将表达式包装在括号中,所以整个事情可以是这样的

table = Assignment.arel_table
where(
  table[:from].gt(date.at_end_of_week).
  or(
    table.grouping(table[:to].not_eq(nil).and(table[:to].lt(date.at_end_of_week)))
  ).not
)

也许可以避免使用
not
,但在我的情况下不行。但无论如何,我的问题不是关于
不是
而是关于分组。
table = Assignment.arel_table
where(
  table[:from].gt(date.at_end_of_week).
  or(
    table.grouping(table[:to].not_eq(nil).and(table[:to].lt(date.at_end_of_week)))
  ).not
)