Complex Arel conditions with AND and OR

I have a question about creating multiple conditions with AND

and OR

in one of the priority operations.

So, I need to generate the following SQL line to navigate to the method 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)

      

I rewrote it with Arel:

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

      

But Arel does not place parentheses around the c clause AND

, and as a result that clause selects the wrong data. How can I put the brackets in this state?

+3


source to share


2 answers


You can use a method table.grouping

to wrap the expression in a parenthesis, so it could all be like



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
)

      

+5


source


you may try:

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

      



I may be missing something, but you should avoid using NOT

in sql or unless

ruby anyway , because this is not good practice

-1


source







All Articles