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

时间:2016-10-01 11:35:45

标签: csv ruby-on-rails-4 rails-activerecord railscasts roo-gem

我试图通过文件导入格式创建记录可以是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 资源:教室做   集合{post:addStudents}

csv文件我正在尝试加载

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

1 个答案:

答案 0 :(得分:0)

这可能是因为#to_hash没有返回具有无差别访问权限的哈希值。您正在尝试将符号化的键和#to_hash创建的键切片为字符串。

试试这个:

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