1

I have a URL in a Rails application that can look like a simple /resource or a more complex /resource?page=3&sort=id&direction=asc. The data behind the view can be exported by appending .tsv to the resource name - /resource.tsv?page=3&sort=id&direction=asc. To do this, I use this call in my .erb: add_extension_to_url(request.original_url, '.tsv') where I have:

module ResourceHelper
  def add_extension_to_url(url, extension)
    query_start = url.index('?')
    if query_start.present?
      url.insert(query_start, extension)
    else
      url + extension
    end
  end
end

It works, but it's not pretty. Am I missing something like request.query_string that gives me what comes after the question mark in the URL?

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
  • Is this what you're looking for? http://stackoverflow.com/questions/2695538/add-querystring-parameters-to-link-to – Ege Ersoz May 27 '14 at 05:55
  • The idiomatic rails way would be using url helpers (from routing system). Something like `order_path(@order, format: :tsv)`. If you need to preserve existing query string, then something like this should work: `order_path(@order, params.merge(format: :tsv))`. Your url mangling method has one advantage: it's generic. But it's not idiomatic. – Sergio Tulentsev May 27 '14 at 05:56
  • @enragedcamel: no, not that. @sergio: [params.merge is not a good idea](http://stackoverflow.com/questions/12271218/params-merge-and-cross-site-scripting), it seems. However, `format: :tsv` looks promising and something I wasn't aware of, so perhaps you could post that as an answer? – Ken Y-N May 27 '14 at 08:33

1 Answers1

1

What you call "extension" is "format" in Rails' terms. You can specify format when generating urls using routing system. Something like:

order_path(@order, format: :tsv)

If you want to preserve an existing query string (with sorting, pagination and whatnot), you can do like this

order_path(@order, params.merge(format: :tsv))

As for the security concerns, you should be fine as long as you filter params so that it only contains expected values. The idiomatic way for this is to use strong_parameters (included in Rails 4).

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367