If you came to this page directly, you may be confused! The code below is related to this post For more details and usage, see there.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# Given a hash that's built from an HTML form, this little gadget # will build an appropriate chunk of SQL to be used in a # :conditions => call. # # input is the hash we got from the form # conjunction is whatever we stick between our conditions, # defaulting to AND name is the optional name for the left-hand side # of the condition. # # This is necessary for inner arrays. def build_conditions(input, conjunction = "AND", name = nil) cond = "" values = [] input.collect { |k,v| # Problem is, all forms come back with a key, but if the value # is blank, we want to move on next if v == "" # If there's already something in the conditions string, we # need to tack on our conjunction. We can't get into a # position where the conjunction ends the string, since we # output everything lower. cond << " #{conjunction} " unless cond.empty? if v.class == Array && v.size > 1 ret = build_conditions(v, "OR", k) cond << "(#{ret})" else cond << "#{name.nil? ? k : name} = ?" end values << v } return [cond, values].flatten end |