close
tony / Working With URLs

Hypertext Rails: Working With URLs

A common requirement with an html first app is to retain the url state as a user clicks around. For example, if a page has a set of scopes and a set of filters, when you're building the link to a scope, you'll want to make sure it also includes the currently active filter.

Hypertext Rails already has these helpers added.

# /app/helpers/application_helper
def current_url_with(params)
  url_for(request.query_parameters.merge(params))
end

def current_params_with(params)
  request.query_parameters.merge(params)
end

Now when we're building a link, to retain the current url parameters we can do this.

<a href="<%= current_url_with(scope:'draft') %>">
  Draft 
</a>
<a href="<%= current_url_with(scope:'active') %>">
  Active 
</a>

You may also want to do this with a named path. In which case you can use

<a href="<%= projects_path(current_params_with(scope:'draft')) %>" >
  Draft Projects 
</a>

If you want to use a named route and keep the query parameters but not update any of them, you can use request.query_parameters like this.

<a href="<%= projects_path(request.query_parameters) %>" >
  Projects 
</a>