Search code examples
ruby-on-railsrubycsvlibreoffice

Unknow attribute 'headers ...' during CSV import on Rails


I have a problem since I try to import my CSV created with Numbers on Mac,

Everything worked before on Ubuntu with LibreOffice,

When I try to import my CSV file I have error

unknown attribute 'adress   user_id room_type etc...' for Bien.

I think it not detect separators and take the first hearder line rows as one string.

My import function:

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    @bien = Bien.create! row.to_hash
    @bien.save
  end 
end

I would know how import the file and if I have things to change when I create my CSV on Numbers.

UPDATE csv

enter image description here


Solution

  • I think you're exactly right, it looks like the separators are not being respected so the header row is showing as one long string. To debug, you can try putting a pry in and running CSV.read(file.path) to see the whole output of the conversion to CSV. Once you do that, you should be able to see what Numbers uses for separators.

    This post suggests Numbers uses semicolons as default separators, so if you define your col_sep: ';' as an option, that might do the trick. (Ref: CSV docs).

    So, the code would be

    def self.import(file)
      CSV.foreach(file.path, col_sep: ';', headers: true) do |row|
        @bien = Bien.create! row.to_hash
        @bien.save
      end 
    end