Tintin81 Tintin81 - 4 months ago 8
Ruby Question

How to pass GET parameters to next controller action in Ruby on Rails?

In my Rails 4.2 app I have an

index
action that lists all the user's invoices, filtered by search parameters in the URL:

class InvoicesController < ApplicationController

def index
@invoices = current_user.invoices.search(params)
respond_to do |format|
format.html do
@title = "Invoices"
...
end
format.csv do
headers['Content-Disposition'] = "attachment; filename=\"#{invoices_filename}.csv\""
end
format.xls do
headers['Content-Disposition'] = "attachment; filename=\"#{invoices_filename}.xls\""
end
end
end

...

end


This works nicely. The user can filter his invoices by various parameters and the listed invoices adjust accordingly.

The problems start when the user wants to download these exact invoices in XLS or CSV format. I have a link for that on
index.html.erb
:

<%= link_to "Download invoices", invoices_path(:format => "xls") %>


However, it downloads all the invoices, not just the ones the user filtered out previously.

Is there a way to pass the search params on to the next action or maybe a more elegant solution all together?

Thanks for any help.

Answer

You just need to send the params along with the format

This will do the trick:

<%= link_to "Download invoices", invoices_path(params.merge(format: :xls)) %>