Arel AND子句和空条件

时间:2015-06-20 07:00:35

标签: ruby-on-rails ruby activerecord arel

考虑以下代码片段:

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子句效果? 还有,有更好的方法来处理这种情况吗?

3 个答案:

答案 0 :(得分:6)

你应该返回true。当你运行.and(true)时,它最终将被转换为' AND 1'在sql。

def filter_by_merchant
  return true if @merchant_id.blank?

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

答案 1 :(得分:1)

似乎无法向and提供导致它什么也不做的任何参数。但是,您可以有条件地致电and

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

它非常笨重,但它完成了工作。

答案 2 :(得分:1)

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