Nested structures with build_query_string

hi all!

just recently i encountered a problem when giving a hash to
ActionController::Base#url_for that itself includes a hash, e.g.,
{:action => ‘search’, :query => {:field1 => ‘value1’, :field2 =>

the corresponding URL looks like

however, the URL built by url_for looks like this:
“/search?query=field1value1field2value2&commit=Search” – which is
obviously incorrect.

this is caused by ActionController::UrlRewriter#build_query_string,
which does recognize arrays, but not hashes. rewriting that method
to build the query string recursively for nested structures lead to
the following:

---- snip ----
def build_query_string(hash, only_keys = nil)
elements = []

build_element = lambda { |key, value|
# skip empty params
return if value.nil? or value.empty?

case value
  when Array
    value.each { |v| "#{key}[]", v
  when Hash
    value.each_pair { |k, v| "#{key}[#{k}]", v
    elements << "#{key}=#{Routing.extract_parameter_value(value)}"


(only_keys || hash.keys).each { |key| CGI.escape(key.to_s), hash[key]

elements.empty? ? ‘’ : ‘?’ + elements.join(‘&’)
---- snip ----

this works for the above mentioned case, nonetheless a few questions

  1. what do you think about this? does it make sense? is it “good” ruby?

  2. where shall i put the modified method? in my lib/ directory i
    have util/extensions/* which all get included in environment.rb –
    this, however, didn’t seem to work. webrick spits out warnings

warning: already initialized constant Helpers
warning: already initialized constant Routes

and i get the following exception: “No url can be generated for the
hash […]”. modifying action_controller/url_rewriter.rb in place
wouldn’t be the preferred way to go, now would it…

thanks for your comments.


Jens W., Dipl.-Bibl. (FH)
prometheus - Das verteilte digitale Bildarchiv für Forschung & Lehre
An St. Laurentius 4, 50931
KölnTel.: +49 (0)221 470-6668, E-Mail: [email protected]