Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 736
Abram Avatar asked Dec 04 '25 04:12

Abram


1 Answers

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) }
like image 117
spickermann Avatar answered Dec 05 '25 20:12

spickermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!