我正在使用Axlsx gem生成Excel工作表。但是,其中两个字段是来自其他模型的ID数组;
health.source_of_power
和**health.service_offered**
@healths.each do |health|
sheet.add_row [District.find(health.district).name,County.find(health.county).name,SubCounty.find(health.sub_county).name,health.name_of_institution,health.money_received,health.date_received,health.use_of_money,health.grade_of_health_center,health.opening_time.strftime("%I:%M %p"),health.closing_time.strftime("%I:%M %p"),health.service_offered,health.other_service_offered,health.male_patients,health.female_patients,health.brick_and_wattle,health.mad_and_wattle,health.other_structures,health.source_of_power,health.other_source_of_power,health.toilet_facilities,health.alternative_disposal,health.separate_toilets,health.running_water,health.alternative_water,health.state_of_water,health.duration_non_functional,health.placenta_pit,health.placental_disposal,health.waste_pit,health.waste_disposal,health.storage_expired_drugs,health.expired_drugs_storage,health.pregnant_mother,health.number_of_beds,health.delivery_beds,health.ambulance,health.status_of_ambulance,health.keep_records,health.number_of_staff,health.medical_staff,health.resident_medical_staff]
end
如何通过遍历数组生成字段名称列表。
答案 0 :(得分:0)
我猜你想在一个单元格中找到一个名单。假设你有一个代表权力来源的Employee
模型(改变你的任何东西),只需找到并映射id:
Employee.where(id: health.source_of_power).pluck(:name).join(',')
或者,如果你有第一个和最后一个:
Employee.where(id: health.source_of_power).pluck(:first, :last).map {|t| t.join(' ')}.join(', ')
如果您提前获得了员工的索引哈希,那么您可以提高效率。然后,您不是每行运行查询:
employees_by_id = Employee.all.index_by(&:id)
@healths.each do |health|
sources_of_power = employees_by_id.values_at(health.source_of_power).map(&:name)
sheet.add_row [...,sources_of_power,...]
end
如果健康对象在那里,您可以使用范围和关系。你的信息有点模糊。