Abram
Abram

Reputation: 41884

Unknown Attribute when importing from CSV

I am trying to do the following in IRB:

file = CSV.read('branches.csv', headers:true) 
file.each do |branch|
  Branch.create(attributes:branch.to_hash)
end

branches.csv contains one header entitled business_name which should map onto the attribute for Branch of the same name, but I see the error:

ActiveRecord::UnknownAttributeError: unknown attribute 'business_name' for Branch.

Strangely, doing Branch.create(business_name:'test') works just fine with no issues.

Update:

enter image description here

enter image description here

I think this has something to do with the encoding of the text in the UTF-8 CSV produced by Excel as suggested in the comments below. Not sure if this IRB gives any clues... but our header title business_name != "business_name"

2.3.3 :348 > file = CSV.read('x.csv', headers:true)
#<CSV::Table mode:col_or_row row_count:165>
2.3.3 :349 > puts file.first.to_hash.first.first
business_name
2.3.3 :350 > file = CSV.read('x.csv', headers:true)
#<CSV::Table mode:col_or_row row_count:165>
2.3.3 :351 > puts file.first.to_hash.first.first == "business_name"
false

Upvotes: 3

Views: 652

Answers (1)

spickermann
spickermann

Reputation: 106882

Just skip the attributes: part. It is not needed at all, because branch.to_hash already returns exactly the format you describe in your last sentence.

file = CSV.read('branches.csv', headers:true) 
file.each { |branch| Branch.create(branch.to_hash) }

Upvotes: 1

Related Questions