2016-10-01 43 views
0

我试图通过文件导入格式创建记录可以是csv excel等 并且我已经在Railscast396之后实现了它。但是当我导入文件时,它说 “验证失败:邮箱不能为空,密码不能为空这里是我的代码使用Roo gem和以下railscast创建记录通过文件导入时的验证问题

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 

观点是

<%= form_tag addStudents_classrooms_path, multipart: true do %> 
    <%= file_field_tag :file %> 
    <%= submit_tag "Import" %> 
<% end %> 

的routes.rb 资源:教室做 集合{职位:addStudents}

csv文件我试图加载

id,email,password,password_confirmation 
22,[email protected],password,password 
23,[email protected],password,password 
+0

是什么row.to_hash.slice的'输出(* attr_names)' – Alfie

+0

其{},可以请你告诉我,为什么会出现这种情况 –

回答

0

这可能发生,因为#to_hash不返回与冷漠访问的哈希值。您正在尝试将符号化的键和#to_hash创建的键作为字符串。

试试这个:

def self.attr_names 
    %w(email password password_confirmation) 
end 
相关问题