Ransack export results to CSV

邮差的信 提交于 2019-11-30 15:46:24

问题


I'm trying to export a list of Ransack (Railscast) results to a CSV file (Railcast). However, it keeps exporting all of the objects, instead of the results returned by the Ransack search. Can anyone tell me where I'm going wrong?

In the Reports controller, I've tried passing both @bookings and @search.result:

  def index
    @search = current_user.bookings.search(params[:q])
    @bookings = @search.result
    @search.build_condition
    respond_to do |format|
      format.html 
      format.csv { render text: Booking.to_csv(@bookings) }\
    end
  end

And then the Booking to_csv method:

  def self.to_csv list
    CSV.generate do |csv|
      csv << column_names
      list.each do |booking|
        csv << booking.attributes.values_at(*column_names)
      end
    end
  end

Yet every time, I get the unfiltered list of current_user.bookings. Why?


回答1:


To export only the filtered results as csv, you should make sure that the search parameters are included in the url you call to generate the csv.

Hence, if you want to export the results that you see on the html page you should call: reports_path(params.merge(format: 'csv')




回答2:


Try this:

def index

  session[:q] = params[:q] if params[:q]
  @search = current_user.bookings.search(session[:q])

  @bookings = @search.result
  @search.build_condition
  respond_to do |format|
    format.html 
    format.csv { render text: Booking.to_csv(@bookings) }\
  end
end


来源:https://stackoverflow.com/questions/16987242/ransack-export-results-to-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!