2014-11-06 41 views
0

我使用Axlsx gem生成Excel表單。但是,其中兩個字段是來自其他模型的ID的數組; health.source_of_power**health.service_offered**使用Axlsx gem生成Xls的Array迭代

@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

試着澄清你的問題。你想爲這些列ID生成xls頭名稱? – blelump 2014-11-06 08:58:01

+0

@blelump,爲Excel工作表生成內容 – user2900061 2014-11-06 21:06:57

回答

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 

如果他們在那裏,你可以在健康對象上使用範圍和關係。你的信息有點模糊。