Combine arrays of conditions in Rails

懵懂的女人 提交于 2019-11-29 02:44:46

Try this:

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]

Edit Approach 2

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

Now you can do this:

cond = []
cond.where("id = ?", params[id]) if params[id].present?
cond.where("state IN (?)", states) unless states.empty?
User.all(:conditions => cond)

I think a better way is to use Anonymous scopes.
Check it out here: http://railscasts.com/episodes/112-anonymous-scopes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!