我们目前遇到一个问题,在下载CSV文件后,重新加载页面时,我们收到错误。潜水时,我发现这是因为返回的数据缺少我们从CSV文件中删除的三列。我们的搜索字段需要deleted_at
列。我有点想知道为什么会这样。
这是我们控制器索引上的代码:
def index
@q = Client.with_deleted.search(session[:clients_q])
#the deleted_at_present is what causes the error, because the deleted_at becomes missing after the csv download
if @q.deleted_at_present.blank?
@q.deleted_at_present = false
end
@page =params[:page]
@clients = @q.result(distinct: true).page(@page)
respond_to do |format|
format.html
format.csv { send_data @q.result(distinct: true).to_csv, :filename => NKF.nkf('-s',"#{Client.model_name.human.titleize}_#{Time.now.strftime("%Y%m%d_%H%M%S")}.csv") }
end
end
这是在模型rb中创建csv的代码:
def self.to_csv
CSV.generate(force_quotes: true) do |csv|
csv << csv_column_names_i18n
all.each do |client|
csv << client.csv_column_values
end
end
end
def self.csv_column_names
csv_column_names = self.column_names
csv_column_names.delete('updated_at')
csv_column_names.delete('created_at')
csv_column_names.delete('deleted_at')
return csv_column_names
end
def self.csv_column_names_i18n
require 'nkf'
require 'kconv'
csv_column_names = self.csv_column_names
return_column_names = []
csv_column_names.each do |csv_column_name|
return_column_names << NKF.nkf('-s',self.human_attribute_name(csv_column_name.to_sym))
end
return return_column_names
end
def csv_column_values
require 'nkf'
require 'kconv'
return_column_values = []
self.attributes.except('updated_at','created_at','deleted_at').each do |key, value|
if key == 'id' || value.nil?
return_column_values << value
else
return_column_values << NKF.nkf('-s',"#{value}")
end
end
return return_column_values
end
答案 0 :(得分:3)
这里的问题看起来像是在self.csv_column_names
方法中。您正在抓取参考至self.column_names
,因此当您致电delete
时,您实际上是从self.column_names
删除。因为它在类方法上进行了更改,所以它会在请求中持续存在。
尝试将方法的第一行更改为:
csv_column_names = self.column_names.dup
请注意.dup
。另一种方法是:
def self.csv_column_names
column_names - %w[updated_at created_at deleted_at]
end