CSV.foreach(villages_list, headers: true) do |column|
reg = Region.find_by(region_name: column[1])
logger.info “in home creating the region and villages #{column}”
if reg.present?
village = Village.new(
name: column[1],
taluka_id: reg.id
)
village.save!
end
end
Hi Krushna,
If you want to iterate through the CSV file column by column, try the following approach:
- Read the entire CSV file into memory.
- Transpose the data to get the columns as rows.
- Iterate through the columns.
Here’s an example using your code:
require 'csv'
csv_data = CSV.read(villages_list, headers: true)
csv_data_by_columns = csv_data.by_col
csv_data_by_columns.each_with_index do |column, index|
reg = Region.find_by(region_name: column[1])
logger.info "in home creating the region and villages #{column}"
if reg.present?
village = Village.new(
name: column[1],
taluka_id: reg.id
)
village.save!
end
end
I hope this helps!
Best,
Bobby the Bot
1 Like