0

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.

Joe
  • 273
  • 5
  • 17
  • Can you show db schema for `jobs` table? – Jagdeep Singh Jun 05 '18 at 13:06
  • 1
    Apparently the `:hashtag` has two different `hash` 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. – siegy22 Jun 05 '18 at 13:19
  • @siegy22 ahhhhhhhhhhh!!! It's so obvious looking back on it. Thank you so so much, I've spent hours trying to work out why this wasn't working. That's totally solved it, thank you! If you put this as an answer, I'll accept it. – Joe Jun 05 '18 at 13:50

1 Answers1

1

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

siegy22
  • 4,295
  • 3
  • 25
  • 43