Foliosus Web Design LLC: Your website done right

Blogfolio

HOWTO: Create a new link by munging the current URL in Rails

Mar 20 ’09

I've been working on a restful app that allows very complicated searches. I've been composing scopes to build the searches, but that's another post. All searches use the index action of the resource's controller. I wanted to offer RSS feeds for every possible search, to allow users to really get only the information they are interested. But I couldn't figure out how to generate the custom RSS feed link easily. I could have gone through my list of scopes, and then re-created the URL with :format => :rss, but that's not very DRY. It turns out that there's a much easier way.

Put the following (or something like it), in the <head> section of your output:

<%= auto_discovery_link_tag(:rss, {:overwrite_params => {:format => :rss}}, {:title => 'RSS feed for this search'}) %>

The magic here is the :overwrite_params parameter that gets passed into url_for to generate your URL. It tells url_for to preserve the current URL, exactly as it is, except for the changes specificed: in this case, switch the format to .rss. This is super-helpful behavior because it preserves GET params, like the arbitrary search parameters my users have input to get to this page.

Since :overwrite_params is used by url_for, any methods based on url_for can handle it: link_to is a great example.

Hooray for easy URL munging!

    Start the conversation

    * indicates a required field

    New comment

    Will never be disclosed or used inappropriately

    Enter the word how to confirm that you are a human being

    About the author

    Brent Miller is the owner and principal web designer of Foliosus Web Design LLC in Portland, Oregon. He enjoys food, plants, and the color green. If you are interested in hiring him for web work, please contact him.

    Categories

    Plant of the day

    Alnus rhombifolia (Betulaceae); White alder

    Alnus rhombifolia (Betulaceae); White alder

    Fresh photos