Get url for current page, but with a different format

后端 未结 3 1950
我寻月下人不归
我寻月下人不归 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:23

    You can use:

    link_to "text of link", your_controller_path(format:'csv',params: request.query_parameters)
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-04 02:40

    @floor's answer was great, I found it very useful.

    Although the method can be improved by using the to_params method rather than contructing your own, like so:

    def current_url(new_params)
      params.merge!(new_params)
      "#{request.uri}#{params.to_params}"
    end
    
    0 讨论(0)
提交回复
热议问题