0

我正在尝试通过文件导入格式创建记录,可以是 csv excel 等,我已经按照 Railscast396 实现了它。但是当我导入文件时,它显示“验证失败:电子邮件不能为空,密码不能为空。这是我的代码

    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 资源 :classrooms 收集 { post :addStudents }

我正在尝试加载的 csv 文件

id,email,password,password_confirmation
22,jim@gmail.com,password,password
23,jimhanks@gmail.com,password,password
4

1 回答 1

0

这可能正在发生,因为#to_hash不会返回具有无关访问的哈希。您正在尝试将符号化键和#to_hash创建的键分割为字符串。

尝试这个:

def self.attr_names
  %w(email password password_confirmation)
end
于 2016-10-02T00:25:18.970 回答