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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With