ruby on rails - How can show message error in a view, when upload a excel file? -
i'm trying show message on new view
here live demo:
http://code.runnable.com/vruvfzpoiivootau/importing-excel-files-for-ruby-on-rails
here controller:
def new end def create @errors = user.import(params[:file]) if @errors.present? render :new; return; end end
here view
import <%= form_tag user_management_users_path, multipart: true %> <%= file_field_tag :file %> <%= submit_tag "import" %> <% end %> <% if @errors %> <% @errors.each |message| %> <%= message %> <% end %> <% end %>
here model:
def self.import(file) @errors = [] spreadsheet = open_spreadsheet(file) (2..spreadsheet.last_row).each |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 on successful save else user.errors.full_messages.each |message| @errors << "issue line #{i}, column #{message}" end end end end def self.open_spreadsheet(file) case file.extname(file.original_filename) when ".csv" roo::csv.new(file.path, csv_options: {encoding: "iso-8859-1:utf-8"}) when ".xls" roo::excel.new(file.path, packed: false, file_warning: :ignore) when ".xlsx" roo::excelx.new(file.path, nil, :ignore) else raise "unknown file type: #{file.original_filename}" end
end
i'm trying find way show message indicating row problem on index view.
for example i'm adding user exist , want show message indicating
row 1 exist row 2 duplicated row 1 must string or
but after uploading excel getting numbers , not message:
issue line 2, column exist issue line 3, column exist
just getting numbers:
2 3
if user can't saved means failed validation (although validation have @ moment on doc_nat
... may want add validations "must string" conditions, etc).
for active_record object failed validation, there's array object.errors.full_messages
errors found when validating.
so...
def self.import(file) @errors = [] spreadsheet = open_spreadsheet(file) (2..spreadsheet.last_row).each |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 on successful save else user.errors.full_messages.each |message| @errors << "la información de la línea #{i}, columna #{message}" end end end @errors # <- need return @errors array end
and in view...
<% if @errors %> <% @errors.each |message| %> <%= message %> <% end %> <% end %>
Comments
Post a Comment