请考虑以下代码片段:
- 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
在方法filter_by_merchant中,当商家ID变为空时,Arel必须返回的值应该忽略AND子句效果?
还有,有更好的方法来处理这种情况吗?
解决方法
你应该返回true.当你运行.and(true)时,它最终会在sql中转换为’AND 1′.
- def filter_by_merchant
- return true if @merchant_id.blank?
- billing_requests[:merchant_id].eq(@merchant_id)
- end