Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get url for current page, but with a different format

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"

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.

cheers, max

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.

like image 976
Max Williams Avatar asked May 06 '11 15:05

Max Williams


2 Answers

<%= 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

like image 136
fl00r Avatar answered Oct 31 '22 13:10

fl00r


You can use:

link_to "text of link", your_controller_path(format:'csv',params: request.query_parameters)
like image 31
Oscar García Avatar answered Oct 31 '22 12:10

Oscar García