0

Axlsx gem を使用して Excel シートを生成しています。ただし、フィールドのうちの 2 つは、他のモデルの 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

配列を反復処理して、フィールドの名前のリストを生成するにはどうすればよいですか。

4

1 に答える 1

0

1 つのセルに名前のリストが必要だと思います。Employee動力源を表すモデルがあると仮定して(自分のものに変更してください)、id を見つけてマップするだけです。

Employee.where(id: health.source_of_power).pluck(:name).join(',')

または、first と last がある場合:

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

ヘルス オブジェクトにスコープと関係がある場合は、それを使用できます。あなたの情報は少し曖昧です。

于 2014-11-07T15:57:38.647 に答える