考虑以下代码片段:
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
关于ruby-on-rails - Arel AND 子句和 Empty 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30951241/