Get url for current page, but with a different format

后端 未结 3 1967
我寻月下人不归
我寻月下人不归 2021-01-04 02:14

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 b

3条回答
  •  暖寄归人
    2021-01-04 02:37

    <%= link_to "This page in CSV", {:format => :csv } %>
    <%= link_to "This page in PDF", {:format => :pdf } %>
    <%= link_to "This page in JPEG", {:format => :jpeg } %>
    

    EDIT

    Add helper

    def current_url(new_params)
      url_for :params => params.merge(new_params)
    end
    

    then use this

    <%= link_to "This page in CSV", current_url(:format => :csv ) %>
    

    EDIT 2

    Or improve your hack:

    def current_url(new_params)
      params.merge!(new_params)
      string = params.map{ |k,v| "#{k}=#{v}" }.join("&")
      request.uri.split("?")[0] + "?" + string
    end
    

    EDIT

    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

提交回复
热议问题