Converting URL to JSON version?

筅森魡賤 提交于 2019-12-09 12:28:46

问题


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'

回答1:


try this :

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

(as seen in this API doc)

alternatively :

user_path( :id => @user.id, :format => :json )



回答2:


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)


来源:https://stackoverflow.com/questions/8494255/converting-url-to-json-version

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!