Reputation: 117
I am trying to create records through file imports format can be csv excel etc and I have implemented it following the Railscast396. but as I import file it says "Validation failed: Email can't be blank, Password can't be blank. Here is my code
class Student < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_many :quizzes
has_many :classrooms
#to import file
**def self.attr_names
[:email, :password, :password_confirmation]
end**
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]
row.inspect
student = find_by_id(row["id"]) || new
student.attributes = row.to_hash.slice(*attr_names)
student.save!
end
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when ".csv" then Roo::CSV.new(file.path, file_warning: :ignore)
when ".xls" then Roo::Excel.new(file.path, file_warning: :ignore)
when ".xlsx" then Roo::Excelx.new(file.path, file_warning: :ignore)
else raise "Unknown file type: #{file.original_filename}"
end
end
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
view is
<%= form_tag addStudents_classrooms_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
routes.rb resources :classrooms do collection { post :addStudents }
csv file i am trying to load
id,email,password,password_confirmation
22,[email protected],password,password
23,[email protected],password,password
Upvotes: 0
Views: 410
Reputation: 6753
This is probably happening because #to_hash
doesn't return a hash with indifferent access. You're trying to slice symbolized keys and #to_hash
created keys as strings.
Try this:
def self.attr_names
%w(email password password_confirmation)
end
Upvotes: 0