Aurick
Aurick

Reputation: 321

Validation in form?

I am trying to do validation but didnot find the right way while uploading the excel

Code for view

<%= form_for :dump, :url=>  import_csv_index_path, :html => { :multipart => true } do |f| %>
<% if (-----).errors.any? %>
<div id="error_explanation">
 <%= pluralize((----).errors.count, "error") %> prohibited this link from being saved:

<% (---).errors.full_messages.each do |msg| %>
<li><%= msg %></li>
</div>

<% end %>

    <%= f.label :'Select an Excel File:'  %>
    <%= f.file_field :file %>
    <i href="#" id="blob_1" class="icon-info-sign" rel="popover" style="margin-top: 300px"></i><br/>

    <%= submit_tag 'Submit' ,:id => 'submit',:class =>"btn btn-primary"%><br/><br/>

<% end -%>

Code for model:

class Person < ActiveRecord::Base

 attr_accessible :date, :email, :name, :avatar ,:template_id

 validates_presence_of :email,:message => 'Email is compulsory' 

end

What do i write at place of (-----)

Thank you

Upvotes: 2

Views: 87

Answers (2)

Aurick
Aurick

Reputation: 321

I have done with the other approach so discuss here,

Code for controller:

 def import

   @error = []
   @error = Person.import(params[:dump][:file])
 redirect_to people_path, notice: "Employees imported.",:flash => { :error =>   "Employees(   Email : invalid/blank) are not saved : #{@error.join("  , ")}" }
end

In model:

def self.import(file)

 spreadsheet = open_spreadsheet(file)
  @err = []
  @alt = []

  header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    @person = Person.find_by_id(row["id"]) ||Person.new



 @person.name = row["Name"].to_s
    @person.date = row["Date"]
    @person.email = row["Email"]



  if @person.save

     else
        @err << {:name => row["Name"].to_s,:error => @person.errors.messages}
     end

    end
    @err.each do |t|



   @alt.push(t[:name])


    end

  return @alt

end

and call that as flash message...and working fine now.

Thanks

Upvotes: 2

Marco
Marco

Reputation: 644

I think somewhere in your controller you have to call .validate on a new instance of your Person model with your form's data. You can save that model in an instance variable that you can put in place of the (-----).

Upvotes: 1

Related Questions