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
)