7

On all the pages of my app, I want a link to the JSON version of current page. Any neat tricks to do this? Where it got complicated was when additional '&' parameters were included in the URL.

So the urls would be transposed as:

'/users' => '/users.json'

'/users?page=1&per_page=5' => '/users.json?page=1&per_page=5'
Carson Cole
  • 4,183
  • 6
  • 25
  • 35

2 Answers2

13

try this :

polymorphic_path( @user, :format => :json )

(as seen in this API doc)

alternatively :

user_path( :id => @user.id, :format => :json )
m_x
  • 12,357
  • 7
  • 46
  • 60
  • I need the link to the JSON version on every page, so the link would be different for that page's path and I may have one, or many associated objects. Is there a way to just git the named path of the current page and append the :format => :json? – Carson Cole Dec 13 '11 at 22:54
  • i found [this question](http://stackoverflow.com/questions/5913525/get-url-for-current-page-but-with-a-different-format), should help you – m_x Dec 14 '11 at 00:07
  • also, when i need to set the locale but to keep the current page, i use `url_for( :locale => :en )` for example. It works with `:locale`, so maybe it will work with `:format` – m_x Dec 14 '11 at 00:18
  • thanks. The link you posted didn't totally work with Rails 3.1, but I was able to figure it out. Edited above. – Carson Cole Dec 14 '11 at 15:33
10

Attribution for this answer from Get url for current page, but with a different format, with modifications:

Helper:

def current_url(new_params)
 url_for params.merge(new_params)
end

Link:

<%= link_to "JSON of this page", current_url(:format=>:json)
Community
  • 1
  • 1
Carson Cole
  • 4,183
  • 6
  • 25
  • 35
  • as said in the question you quote, you should duplicate params before using them. Anyway, feel free to accept your own answer. – m_x Dec 14 '11 at 17:32
  • What was different was the requirement for "url_for :params => params.merge(new_params)", instead of just "url_for params.merge(new_params)". – Carson Cole Dec 14 '11 at 20:32