Ransack 将结果导出到 CSV [英] Ransack export results to CSV
问题描述
我正在尝试导出 Ransack (Railscast) 结果列表到 CSV 文件(Railcast).但是,它会不断导出所有对象,而不是 Ransack 搜索返回的结果.谁能告诉我哪里出错了?
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?
在报告控制器中,我尝试同时传递@bookings 和@search.result:
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
然后是 Booking to_csv 方法:
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
然而,每次我都会得到未经过滤的 current_user.bookings 列表.为什么?
Yet every time, I get the unfiltered list of current_user.bookings. Why?
推荐答案
要仅将过滤后的结果导出为 csv,您应该确保在您调用以生成 csv 的 url 中包含搜索参数.
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.
因此,如果您想导出您在 html 页面上看到的结果,您应该调用:reports_path(params.merge(format: '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')
这篇关于Ransack 将结果导出到 CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!