在 Rails 中组合条件数组 [英] Combine arrays of conditions in Rails
问题描述
我正在使用 Rails3 测试版、will_paginate gem 和 geokit gem &插件.
I'm using the Rails3 beta, will_paginate gem, and the geokit gem & plugin.
作为 geokit-rails 插件,似乎不支持 Rails3 范围(包括 :origin 符号是问题),我需要使用 .find 语法.
As the geokit-rails plugin, doesn't seem to support Rails3 scopes (including the :origin symbol is the issue), I need to use the .find syntax.
代替范围,我需要以数组格式组合两组条件:
In lieu of scopes, I need to combine two sets of criteria in array format:
我有一个默认条件:
conditions = ["invoices.cancelled = ? AND invoices.paid = ?", false, false]
我可能需要将以下条件之一添加到默认条件中,具体取决于 UI 选择:
I may need to add one of the following conditions to the default condition, depending on a UI selection:
#aged 0
lambda {["created_at IS NULL OR created_at < ?", Date.today + 30.days]}
#aged 30
lambda {["created_at >= ? AND created_at < ?", Date.today + 30.days, Date.today + 60.days]}
#aged > 90
lamdba {["created_at >= ?", Date.today + 90.days]}
结果查询类似于:
@invoices = Invoice.find(
:all,
:conditions => conditions,
:origin => ll #current_user's lat/lng pair
).paginate(:per_page => @per_page, :page => params[:page])
问题:
- 是否有一种简单的方法来组合这两个条件数组(如果我的措辞正确的话)
- 虽然它不会导致问题,但是否有更干燥的方法来创建这些老化的存储桶?
- 有没有办法将 Rails3 范围与 geokit-rails 插件一起使用?
感谢您的时间.
推荐答案
试试这个:
ca = [["invoices.cancelled = ? AND invoices.paid = ?", false, false]]
ca << ["created_at IS NULL OR created_at < ?",
Date.today + 30.days] if aged == 0
ca << ["created_at >= ? AND created_at < ?",
Date.today + 30.days, Date.today + 60.days] if aged == 30
ca << ["created_at >= ?", Date.today + 90.days] if aged > 30
condition = [ca.map{|c| c[0] }.join(" AND "), *ca.map{|c| c[1..-1] }.flatten]
编辑方法 2
Monkey 修补 Array
类.在 config/initializers
目录中创建一个名为 monkey_patch.rb
的文件.
Monkey patch the Array
class. Create a file called monkey_patch.rb
in config/initializers
directory.
class Array
def where(*args)
sql = args[0]
unless (sql.is_a?(String) and sql.present?)
return self
end
self[0] = self[0].present? ? " #{self[0]} AND #{sql} " : sql
self.concat(args[1..-1])
end
end
现在你可以这样做:
cond = []
cond.where("id = ?", params[id]) if params[id].present?
cond.where("state IN (?)", states) unless states.empty?
User.all(:conditions => cond)
这篇关于在 Rails 中组合条件数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!