Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arel AND clause and Empty condition

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?

like image 836
MIdhun Krishna Avatar asked Jun 20 '15 07:06

MIdhun Krishna


2 Answers

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
like image 119
Joshua Avatar answered Sep 25 '22 10:09

Joshua


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.

like image 43
Wally Altman Avatar answered Sep 25 '22 10:09

Wally Altman