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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With