Arel AND clause and Empty condition

1.9k views Asked by At

Consider the following code fragment:

def sql
  billing_requests
  .project(billing_requests[Arel.star])
  .where(
    filter_by_day
      .and(filter_by_merchant)
      .and(filter_by_operator_name)
  )
  .to_sql
end

def filter_by_day
  billing_requests[:created_at].gteq(@start_date).and(
    billing_requests[:created_at].lteq(@end_date)
  )
end

def filter_by_operator_name
  unless @operator_name.blank?
    return billing_requests[:operator_name].eq(@operator_name)
  end
end

def filter_by_merchant
  unless @merchant_id.blank?
    return billing_requests[:merchant_id].eq(@merchant_id)
  end
end

private

def billing_requests
  @table ||= Arel::Table.new(:billing_requests)
end

In method filter_by_merchant when merchant id becomes empty, what should be the value that must be returned for Arel to ignore the AND clause effect? Also, is there a better way to handle this case?

3

There are 3 answers

5
Wally Altman On

It doesn't seem to be possible to give any arguments to and that cause it to do nothing. However, you can just call and conditionally:

def sql
  billing_requests
  .project(billing_requests[Arel.star])
  .where(filter_by_day_and_merchant_and_operator_name)
  .to_sql
end

def filter_by_day
  billing_requests[:created_at].gteq(@start_date).and(
    billing_requests[:created_at].lteq(@end_date)
  )
end

def filter_by_merchant
  billing_requests[:merchant_id].eq(@merchant_id)
end

def filter_by_operator_name
  billing_requests[:operator_name].eq(@operator_name)
end

def filter_by_day_and_merchant
  if @merchant_id.blank?
    filter_by_day
  else
    filter_by_day.and(filter_by_merchant)
  end
end

def filter_by_day_and_merchant_and_operator_name
  if @operator_name.blank?
    filter_by_day_and_merchant
  else
    filter_by_day_and_merchant.and(filter_by_operator_name)
  end
end  

private

def billing_requests
  @table ||= Arel::Table.new(:billing_requests)
end

It's extremely clunky, but it gets the job done.

1
Joshua On

You should return true. When you run .and(true) it will eventually get converted to 'AND 1' in the sql.

def filter_by_merchant
  return true if @merchant_id.blank?

  billing_requests[:merchant_id].eq(@merchant_id)
end
0
coorasse On
def sql
  billing_requests
  .project(billing_requests[Arel.star])
  .where(conditions)
  .to_sql
end

def conditions
  ret = filter_by_day
  ret = ret.and(filter_by_merchant) unless @merchant_id.blank?
  ret = ret.and(filter_by_operator_name) unless @operator_name.blank?
  ret
end

def filter_by_day
  billing_requests[:created_at].gteq(@start_date).and(
    billing_requests[:created_at].lteq(@end_date)
  )
end

def filter_by_operator_name
  billing_requests[:operator_name].eq(@operator_name)
end

def filter_by_merchant
   billing_requests[:merchant_id].eq(@merchant_id)
end

private

def billing_requests
  @table ||= Arel::Table.new(:billing_requests)
end