3

I have a ransack search form which is working wonderfully, I would like to add an export for the user to send the contents of the result set to an XLS file.

I have implemented the to_xls sucessfully as well, however it is giving me back the fullest possible scope of the object I am searching, and not the filtered results that are shown in the view.

def index

  @search = Expense.search(params[:q])
  @expense_list = @search.result.sort_by(&:expense_date) 

    respond_to do |format|
      format.html
      format.xml { render :xml => @expense_list }
      format.xls { send_data @expense_list.to_xls, :filename => '123.xls'}
    end

end

Does it have something to do with how ransack uses the GET method? Any help would be great.

Thanks!

Atari2600
  • 1,219
  • 2
  • 13
  • 26

3 Answers3

3

I know this is such a hack, after spending many hours of not getting it, I used it anyway.

<a href="/expenses.xls?<%= request.fullpath.split("?")[1]  %>">make xls</a>

so basically it takes the searchpath after the ?, then adds it to your model.xls output path and then it works. I hate it myself, there must be a better way, but deadlines.

There was a good link here.

maxcobmara
  • 391
  • 2
  • 9
1

Ronin gave a simple solution to this related question, but with CSV instead of XLS . In my case, using Ronin's answer, I just rewrote the link to work with XLS as shown below

<%= link_to "Download Excel", reports_path(params.merge(format: "xls")) %>
Community
  • 1
  • 1
Musili Alfred M.
  • 3,085
  • 1
  • 15
  • 12
  • Note that since the implemantation of Strong Params in Rails 5 (2016), this needs to be written as: ```link_to 'Download Excel', objects_path( {q: params.require(:q).permit(:attribute_one_eq, :attribute_two_cont)}.merge({format: :xls}))``` – Nick Gobin Jul 24 '23 at 21:51
0
%= link_to "Download Excel", yours_controller_path(params.merge(format: "xls")) %>
  • Welcome to Stack Overflow! Although this code may help to solve the problem, it doesn't explain _why_ and/or _how_ it answers the question. Providing this additional context would significantly improve its long-term educational value. Please [edit] your answer to add explanation, including what limitations and assumptions apply. – Toby Speight Sep 26 '16 at 08:41