我是ROR,我只是想知道如何打印一个带有某些条件的CSV来查询来自我的查询的特定数据?我没有使用一些设计模式,因为我是新手。我只是想知道在轨道上的ruby中打印CSV是否可行。
以下是给定模型中用于打印CSV的示例代码。
def self.cross_mri_transfer_to_csv
attributes = %w{
employee_name
location_assignment
job_grade_position
from_institution
from_cluster
from_region
from_area
from_unit
to_institution
to_cluster
to_region
to_area
to_unit
status
initiated_by
approved_by
endorsed_by
confirmed_by
start_date
applied_at
}
CSV.generate(headers: true) do |csv|
csv << attributes.map{|e| e.split("_").map(&:capitalize).join(' ')}
all.each do |employee_event|
csv << [
employee_event.employee.fullname_formal,
employee_event.location_assignment,
employee_event.job_grade_position,
employee_event.event_data[:old][:institution_name],
employee_event.event_data[:old][:cluster_name],
employee_event.event_data[:old][:region_name],
employee_event.event_data[:old][:area_name],
employee_event.event_data[:old][:unit_name],
employee_event.event_data[:new][:institution_name],
employee_event.event_data[:new][:cluster_name],
employee_event.event_data[:new][:region_name],
employee_event.event_data[:new][:area_name],
employee_event.event_data[:new][:unit_name],
employee_event.status,
if (employee_event.steps.where(step_type: :initiate).first.performed_actor.present?)
employee_event.steps.where(step_type: :initiate).first.performed_actor.fullname_formal.upcase,
else
none,
end
if (employee_event.steps.where(step_type: :approve).first.performed_actor.present?)
employee_event.steps.where(step_type: :approve).first.performed_actor.fullname_formal.upcase,
else
none,
end
if (employee_event.steps.where(step_type: :endorse).first.performed_actor.present?)
employee_event.steps.where(step_type: :endorse).first.performed_actor.fullname_formal.upcase,
else
none,
end
if (employee_event.steps.where(step_type: :confirm).first.performed_actor.present?)
employee_event.steps.where(step_type: :confirm).first.performed_actor.fullname_formal.upcase,
else
none,
end
employee_event.start_date,
employee_event.applied_at
]
end
end
end
我知道代码中存在语法错误。这只是一个演示或示例。但是这可以用于打印CSV吗?对不起这个问题,但我只是想知道,因为我试了一天,但没有找到任何东西:(
感谢有人可以提供帮助。 提前谢谢。
答案 0 :(得分:4)
数组定义中存在语法错误。例如:
[
# ...
employee_event.status,
if (...)
employee_event.steps.where(step_type: :initiate).etc.etc,
else
none,
end
# ...
]
应改为:
[
# ...
employee_event.status,
if (...)
employee_event.steps.where(step_type: :initiate).etc.etc
else
none
end, # <--- !!!!!
# ...
]
您可以将此代码视为“数组元素是if
语句的返回值”。
数组中的每个项必须用逗号分隔,并且每个if
语句只向数组添加一个项。
正如其他人所建议的那样,还有许多其他方法可以改进代码;但这应解决你当前的问题。