Nice(r) Hash treatment for URLs

Isn’t it nice how Rails lets you add form elements using the convention:

store[manager] = Bob Smith
store[location][state] = Wisconsin
store[location][zip] = 53590

And easily process them on the server side with something like:
Store.new(params[:store])

So, why does this:
link_to “Store”, :controller => :store, :action => :show, :store => { :manager => “Bob Smith”, :location => { :state => “Wisconsin”, :zip => 53590 } }

output something stupid like this:
http://localhost:3000/case/1/store/show?store=locationstateWisconsinzip53590managerBob+Smith

when what I’d like is something like:
http://localhost:3000/store/show?store%5Blocation%5D%5Bstate%5D=Wisconsin&store%5Blocation%5D%5Bzip%5D=53590&store%5Bmanager%5D=Bob+Smith

Well, without further ado, I give you the url_for hack to make it happen (note: For a widespread solution this would need to do a bit more… escape things, handle some different object types, handle more than 1 layer of hashed values, etc… but you get the idea)

url_for_hack2.png

Putting this in url_for has other benefits since lots of things depend on it. For example, now you can do:

redirect_to :action => :show, :store => { :manager => “Bob Smith”, :location => { :state => “Wisconsin”, :zip => 53590 } }

This is especially handy if you’d like an action to “hand off” some of the params that it’s received via a redirect.

Advertisements

Leave a comment

Filed under rails, Ruby

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s