-3

我正在尝试在新视图上显示一条消息

这里是现场演示:

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
4

1 回答 1

3

如果无法保存用户,则意味着验证失败(尽管您目前拥有的唯一验证是开启doc_nat......您可能希望为“必须是字符串”条件等添加验证)。

对于验证失败的 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 %>
于 2016-02-06T00:13:47.467 回答