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
是什麼row.to_hash.slice的'輸出(* attr_names)' – Alfie
其{},可以請你告訴我,爲什麼會出現這種情況 –