1

我在 Rails 中有一个带有表格的报告,用户可以选择设置过滤器,例如选择位置或选择日期范围,并通过 ajax 请求更新表格。

我可以写这个 where 子句,以便它有任何日期/空白或所有位置吗?

@orders = Order.where('created_at <= ? AND ? <= created_at AND location_id = ?', date_order_start, date_order_end, loc_filter)

上面的查询在空白处失败(例如,“”),如果我把 nils 转换为 SQL 中的空值。

为了解决这个问题,我现在有一堆条件语句来检查 ajax 请求中是否存在值,然后根据情况创建不同的 where 子句。我目前的条件很笨拙,容易出错并且不可扩展。

搜索“通配符 sql”之类的内容最终导致我进行文本搜索(即 %),我认为这不适合这种情况。

我正在使用 postgresql 在 Rails 3.2 上运行。

4

1 回答 1

2

我有时会使用这样的查询语句和参数数组:

queries = []
args = []
if some_condition
  queries.push("created_at <= ?")
  args.push(whatever_date)
end

if another_condition
  queries.push("created_at >= ?")
  args.push(another_date)
end

@order = Order.where(queries.join(" AND "), *args)
于 2013-10-25T14:33:36.480 回答