我目前有一个控制器,它将使用FasterCSV gem处理将表导出到CSV文件的调用。问题是存储在数据库中的信息有时不清楚,所以我想更改特定列的输出。
我的project.status列例如有数字而不是状态,即数据库中的1对应于Active,2表示非活动,0表示Not Yet。当我导出表时,它显示0,1,2而不是Active,Inactive或Not Yet。知道如何实现这个吗?
我尝试了一个简单的循环来检查最终生成的CSV文件并将每个0,1,2更改为其相应的输出,但问题是每个其他列的0,1,2也会发生变化。我不确定如何隔离色谱柱。 提前致谢
def csv
qt = params[:selection]
@lists = Project.find(:all, :order=> (params[:sort] + ' ' + params[:direction]), :conditions => ["name LIKE ? OR description LIKE ?", "%#{qt}%", "%#{qt}%"])
csv_string = FasterCSV.generate(:encoding => 'u') do |csv|
csv << ["Status","Name","Summary","Description","Creator","Comment","Contact Information","Created Date","Updated Date"]
@lists.each do |project|
csv << [project.status, project.name, project.summary, project.description, project.creator, project.statusreason, project.contactinfo, project.created_at, project.updated_at]
end
end
filename = Time.now.strftime("%Y%m%d") + ".csv"
send_data(csv_string,
:type => 'text/csv; charset=UTF-8; header=present',
:filename => filename)
end
答案 0 :(得分:1)
这实际上相当容易。在您的控制器代码中:
#app/controllers/projects_controller.rb#csv
@lists.each do |project|
csv << [project.descriptive_status, project.name, project.summary, project.description, project.creator, project.statusreason, project.contactinfo, project.created_at, project.updated_at]
end
然后在你的模型代码中。您可能已经有一种方法可以将DB状态解码为更具描述性的方法,但是:
#app/models/project.rb
ACTIVE_STATUS = 0
INACTIVE_STATUS = 1
NOT_YET_DECIDED_STATUS = 2
def descriptive_status
case status
when ACTIVE_STATUS
"Active"
when INACTIVE_STATUS
"Inactive"
when NOT_YET_DECIDED_STATUS
"Not Yet Decided"
end
end
然后可能有很多方法可以重构这个。至少在控制器中,最好使该查找器成为更具描述性的命名范围。模型中的常量可以带入SettingsLogic配置或其他类似的gem。