I'm getting some weird issues. I'm trying to allow importing of a CSV into my model. I'm getting an unknown attribute 'hashtag' for Job.
error, but that's not the issue. My model definitely has a hashtag
column.
When I get the error, if I try doing job.to_hash
I get {"hashtag"=>"apples", "number"=>"10", "job_type"=>"0"}
and if I do job.to_hash.symbolize_keys
(with or without a !
) I get {:hashtag=>"apples", :number=>"10", :job_type=>"0"}
However, here comes the issue. Both of these seem to be of the Hash
class when I call .class
on them. But if I try assigning it to a variable and calling ["hashtag"]
or [:hashtag]
on it, it returns nil
.
Example of what I mean:
>> foo = job.to_hash.symbolize_keys
=> {:hashtag=>"apples", :number=>"10", :job_type=>"0"}
>> bar = {hashtag: "apples", number: "10", job_type: "0"}
=> {:hashtag=>"apples", :number=>"10", :job_type=>"0"}
>> foo == bar
=> false
>> foo.class
=> Hash
>> foo.class == bar.class
=> true
Model:
class Job < ApplicationRecord
require 'csv'
def self.import(file)
file = CSV.read(file.path, headers:true)
file.each { |job| Job.create(job.to_hash)}
end
end
CSV:
hashtag,number,job_type
apples,10,0
bees,10,0
carrots,10,0
I really don't see what's going wrong... I'm literally copying and pasting the foo
variable above into a new variable and it works, yet the original doesn't, despite, despite apparently being a hash as well.
Apparently the :hashtag
has two different encodings for me, seems like one is stored as US-ASCII, and one (the parsed) in UTF-8. Funny that I was able to reproduce this only by pasting this into my irb.
To solve this, make sure they have the same encoding 😄