在 Rails 中组合条件数组 [英] Combine arrays of conditions in Rails

查看:34
本文介绍了在 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])

问题:

  1. 是否有一种简单的方法来组合这两个条件数组(如果我的措辞正确的话)
  2. 虽然它不会导致问题,但是否有更干燥的方法来创建这些老化的存储桶?
  3. 有没有办法将 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆