上传 excel 文件时,如何在视图中显示消息错误?

How can show message error in a view, when upload a excel file?

我正在尝试在新视图中显示消息

这里是现场演示:

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 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

如果无法保存用户,则表示验证失败(尽管您目前唯一的验证是 doc_nat...您可能需要为 [=22= 添加验证] 条件等)。

对于验证失败的active_record对象,有一个数组object.errors.full_messages,它是验证时发现的所有错误。

所以...

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.new(: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 << "La información de la línea #{i}, columna #{message}"
      end
    end
  end 
  @errors #  <- need to return the @errors array   
end

并且在视图中...

<% if @errors %>
  <% @errors.each do |message| %>
    <%= message %>
  <% end %>
<% end %>