我正在尝试在新视图上显示一条消息
这里是现场演示:
http://code.runnable.com/VrUvfZPOiiVooTAU/importing-excel-files-for-ruby-on-rails
这是控制器:
def new
end
def create
@errors = User.import(params[:file])
if @errors.present?
render :new;
return;
end
end
这是视图
Import
<%= form_tag user_management_users_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
<% if @errors %>
<% @errors.each do |message| %>
<%= message %>
<% end %>
<% end %>
这是模型:
def self.import(file)
@errors = []
spreadsheet = open_spreadsheet(file)
(2..spreadsheet.last_row).each do |i|
name = spreadsheet.cell(i,'A')
lastname = spreadsheet.cell(i,'B')
doc_nat = spreadsheet.cell(i,'C')
user = User.create(:name => name,
:lastname =>lastname,
:doc_nat =>doc_nat)
if user.save
# stuff to do on successful save
else
user.errors.full_messages.each do |message|
@errors << "Issue line #{i}, column #{message}"
end
end
end
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when ".csv" then Roo::CSV.new(file.path, csv_options: {encoding: "iso-8859-1:utf-8"})
when ".xls" then Roo::Excel.new(file.path, packed: false, file_warning: :ignore)
when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore)
else raise "Unknown file type: #{file.original_filename}"
end
结尾
我正在尝试找到在索引视图上显示指示 ROW PROBLEM 的消息的方法。
例如,我正在添加一个已经存在的用户并希望显示一条消息,指示
ROW 1 already exist
Row 2 is duplicated
Row 1 must be string
or something like that
但是上传excel后只是得到数字而不是消息:
Issue line 2, column already exist
Issue line 3, column already exist
只是得到数字:
2 3