Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I preserve querystring values across requests in Ruby on Rails?

I'm coming up against one of those moments working with Rails when I feel that there must be a better way than what I'm ending up with.

I have four querystring parameters that I want to preserve across requests through various parts of a rails app - different controllers and actions, some rendered via javascript - so that the user ends up at a URL with the same querystring parameters that they started with.

I'm finding it hard to believe that the best way is through hidden form fields and manually adding the params back in as part of a redirect_to, or using session vars for each - it just seems to un-rails like.

Does anyone know of a better way to manage this?

Thanks!

like image 691
evanmcd Avatar asked Nov 17 '10 04:11

evanmcd


1 Answers

In cases like this, I'll often use a helper function to create urls based on the current set of params. In other words, I'd define this:

def merge_params(p={})
  params.merge(p).delete_if{|k,v| v.blank?}
end

And then use it with url_for to create the urls for your forms and links. If you need to modify and of the params, just pass them into the merge:

# url for the current page
url_for(merge_params)

# url for a different action
url_for(merge_params(:controller => 'bar', :action => 'bar'))

# et cetera
url_for(merge_params(:action => 'pasta', :sauce => 'secret'))

This'll preserve existing params plus whatever overrides you merge in.

like image 131
abscondment Avatar answered Sep 20 '22 21:09

abscondment