How to save query values ​​when querying in Ruby on Rails?

I come to one of those things that work with Rails when I feel that there should be a better way than what I am having.

I have four querystring parameters that I want to save through requests through different parts of the rails application - different controllers and actions, some of which are displayed through javascript, so that the user gets to the URL with the same request parameters that they started with.

It’s hard for me to believe that the best way is to hidden form fields and manually add parameters back as part of redirect_to or use session vars for each - it just looks like un-rails.

Does anyone know how best to deal with this?

Thanks!

+6
query-string ruby-on-rails
source share
3 answers

In such cases, I often use a helper function to create URLs based on the current set of parameters. In other words, I would 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 urls for your forms and links. If you need to change the parameters, just pass them to 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 will preserve the existing options plus any overrides that you combine.

+5
source share

If you want to always save certain parameters for each generated URL, you can implement the default_url_parameters method in your application.

This is poorly documented, but mentioned in the Rails 18n manual

Deploy in application_controller.rb:

 def default_url_options(*args) super.merge( :foo = params[:foo], :bar = params[:bar] ) end 

Now, each URL created by Rails will contain the current request values ​​for foo and bar (unless a URL is created that indicates it is something else special).

+2
source share

Please note that this is not a solution for rails, but works for me in 80% of cases. Here's how I can achieve this with jQuery, obviously, not in the best way. And I can't get it to work for link level 2:

 function mergeGPS(){ var lat = getParam('lat');//localStorage.getItem('lat'); var lng = getParam('lng');//localStorage.getItem('lng'); if(lat == null || lng == null){return false;} var links = jQuery("a"); jQuery.each(links, function(y, lnk){ //debugger; var uri = jQuery(lnk).attr('href') + "?lat="+lat+"&lng="+lng; jQuery(lnk).attr('href',uri); //debugger; }) } function getParam(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } 

mergeGPS must be called when the page loads.

-one
source share

All Articles