I have a Rails view that produces a HTML report based on the user having selected a date range of the report – and all is good with that.
If the users likes what they see, there’s a button to export that same report as csv.
My problem is how to conveniently pass the date range previously selected by the user. I’ve read various stackoverflow questions/answers about passing parameters via link_to, and this works somewhat, but the date is sent as a text string, and what I really need is for the date to be passed as a Date object.
Here’s my current link_to, which passes the date params as strings:
<%= link_to image_tag("Buttons/ExportReport.png", :border => 0),
export_sales_path(:start => @start_date,
:end => @end_date,
:sales => @items) %>
I’d appreciate it if someone could tell me how to pass an instance of an object via link_to.
Thanks for reading.
You can’t pass objects in URLs. For one, there’s a limit of about 1500 bytes on the length of the URL, and secondly, Ruby objects are only relevant to the process that created them.
The important thing to remember here is there is no presumption that the process that will be receiving your request will be the same as the one that generated the page with the link on it. By design, Ruby on Rails starts with a clean slate for each incoming request and has no knowledge apart from what it can extract from three basic facilities: the
cache, thesession, and your database.For things like
@items, what you need to do is save this set somewhere, such as in a database, and put a token or identifier in the URL that links to this saved set, or convert it to a representation that fits in the URL. If the list is small, you could always send@items.collect(&:id).join(',')and then decode that on the receiving end.If all you need is a temporary store, Memcache, which can be used in the
Rails.cachesubsystem, serves as a good place to put things like this.Since dates are easily represented as integers, you could always supply those as the parameters. An approach might look like this:
You can switch this to a
POST-style request which will allow you to supply a very long list of items if required.