使用Roo gem和railscast通过文件导入创建记录时的验证问题



我试图通过文件导入格式创建记录可以是csv excel等并且我已经按照Railscast396实现了它。但当我导入文件时,它说"验证失败:Email不能为空,Password不能为空。这是我的代码

    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 资源:教室做collection {post:addStudents}

csv文件我正在尝试加载

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

这可能是因为#to_hash没有返回具有无关访问的散列。您正在尝试切片符号键和#to_hash创建的键作为字符串。

试试这个:

def self.attr_names
  %w(email password password_confirmation)
end

相关内容

  • 没有找到相关文章

最新更新