问题描述
使用 rails 2. 我想要一个到当前页面的链接(无论它是什么),它保持所有参数相同,但将格式更改为csv".(可以通过在参数中设置 format=csv 或将 .csv 放在路径末尾来设置格式).例如
Using rails 2. I want a link to the current page (whatever it is) that keeps all of the params the same but changes the format to 'csv'. (setting the format can be done by having format=csv in the params or by putting .csv at the end of the path). Eg
posts/1
=> posts/1.csv OR posts/1?format=csv
posts?name=jim
=> posts.csv?name=jim OR posts?name=jim&format=csv
我把这个当成一次黑客尝试
I tried this as a hacky attempt
request.url+"&format=csv"
如果当前 url 中有参数(上面的情况 2),则可以正常工作,但如果没有(情况 1),则会中断.我可以在这些方面想出更多hacky 的东西,例如测试请求是否有参数,但我认为必须有更好的方法.
and that works fine if there are params in the current url (case 2 above) but breaks if there aren't (case 1). I could come up with more hacky stuff along these lines, eg testing if the request has params, but i'm thinking there must be a nicer way.
干杯,最大
编辑 - 顺便说一句,不能保证当前页面可以有一个与之关联的命名路由,以防万一:我们可以通过通用的/:controller/:action/:id"路由到达那里.
EDIT - btw, it's not guaranteed that the current page could have a named route associated with it, in case that's relevant: we could have got there via the generic "/:controller/:action/:id" route.
推荐答案
<%= link_to "This page in CSV", {:format => :csv } %>
<%= link_to "This page in PDF", {:format => :pdf } %>
<%= link_to "This page in JPEG", {:format => :jpeg } %>
编辑
添加助手
def current_url(new_params)
url_for :params => params.merge(new_params)
end
然后使用这个
<%= link_to "This page in CSV", current_url(:format => :csv ) %>
编辑 2
或者改进你的黑客:
def current_url(new_params)
params.merge!(new_params)
string = params.map{ |k,v| "#{k}=#{v}" }.join("&")
request.uri.split("?")[0] + "?" + string
end
编辑
重要!@floor - 你上面的方法有一个严重的问题 - 它直接修改参数,所以如果你在调用这个使用参数的方法后得到任何东西(例如 will_paginate 链接),那么这将得到你使用的修改版本建立你的链接.我将其更改为在 params 上调用 .dup,然后修改重复的对象,而不是直接修改 params.– @Max 威廉姆斯
IMPORTANT! @floor - your approach above has a serious problem - it directly modifies params, so if you've got anything after a call to this method which uses params (such as will_paginate links for example) then that will get the modified version which you used to build your link. I changed it to call .dup on params and then modify the duplicated object rather than modifying params directly. – @Max Williams
这篇关于获取当前页面的 url,但格式不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!