I am following the Import CSV Railscast and it is straight forward.
The issue is that it deals with just a csv file containing only information in 1 model in 1 file.
try this
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
product = find_by_id(row["id"]) || new
product.attributes = row.to_hash.slice(*accessible_attributes)
product.save!
building = product.buildings.find_by_name(row['building_name'])
building ||= product.buildings.build
building.attributes = row.to_hash.slice(*build_accessible_attributes)
building.save!
end
end
UPDATE: updated answers using new rails 3 methods
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
product = where(id: row["id"])
.first_or_create!(row.to_hash.slice(*accessible_attributes))
product.buildings.where(name: row['building_name'])
.first_or_create!(row.to_hash.slice(*building_accessible_attributes))
end
end