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 자료실 : 강의실 컬렉션 {post : addStudents}
csv 파일은 내가 #to_hash
무관심 액세스 할 수있는 해시를 반환하지 않기 때문에이 아마 일어나고
id,email,password,password_confirmation
22,[email protected],password,password
23,[email protected],password,password
이 row.to_hash.slice'의 출력 무엇인가 (* attr_names가) 이런 일이 왜' – Alfie
는 {}, 당신이 나에게 알려 주시기 바랍니다 수 있습니다 –