2

I have an application on which I want to provide the feature to import the records from CSV and Excel file formats. I am using roo gem for it, but at the time of importing it gives the error "undefined method `[]' for nil:NilClass".

Here is the code :

student.rb :

require 'roo'
def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    product = find_by_id(row["id"]) || new
    product.attributes = row.to_hash.slice(*accessible_attributes)
    product.save!
  end
end


def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::CSV.new(file.path, nil, :ignore)
  when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
  when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
end

student_controller.rb :

def import
    Student.import(params[:file])
    redirect_to students_path, notice: "Record imported Successfully."
  end

new.html.erb :

<%= form_tag import_students_path, multipart: true do %>
        <%= file_field_tag :file , :required=> true%> <br/>
        <%= submit_tag "Import" , :class => "btn btn-primary btn-block" %>
<% end %>

Tell me what i am doing wrong?

Nitesh Mishra
  • 570
  • 1
  • 4
  • 18
  • At which line you get the error? – Pavan Jul 08 '15 at 14:57
  • @Pavan In student.rb line no. 4 i.e. " header = spreadsheet.row(1) " – Nitesh Mishra Jul 08 '15 at 17:09
  • Have you tried loading the file on the console with `Roo::CSV.new(file.path, nil, :ignore)` and then calling `. row`? What happens if you do? – dgilperez Jul 08 '15 at 21:39
  • had the same problem, this fix helped me, link is [here](http://stackoverflow.com/questions/26657194/roo-with-rails4-giving-undefined-method-for-nilnilclass) – Sridhar Oct 10 '15 at 05:47
  • Possible duplicate of [Roo with rails4 giving undefined method \`\[\]' for nil:NilClass](https://stackoverflow.com/questions/26657194/roo-with-rails4-giving-undefined-method-for-nilnilclass) – John Moses Jun 17 '17 at 14:21

0 Answers0