Comment on Passing Arrays and Nested Params to url_for in Rails by Andy Triggs

Wed, 17 Oct 2007 04:13:53 -0700

Thanks for this Ryan -- very useful.

To completely preserve the nil functionality (as mentioned by Lon), you also need to limit recursion in the case of nil values, so Hash#process_pair becomes:

def process_pair(key, value)
  elements = []
  if value.is_a?(Array)
    value.each do |element|
      elements += process_pair((key.to_s + '[]').to_sym, element)
    end
  elsif value.is_a?(Hash)
    value.flatten(key).each do |fk, fv|
      elements += process_pair(fk, fv) unless fv.nil?
    end
  elsif !value.nil?
    elements << "#{key.to_s}=#{CGI.escape(process_option_param_value(value).to_s)}"
  end
  elements
end