I am using rails 4. I am having employee attendance model. In that I have to upload .csv file alone. It won't allow any other format. So, How to validate file format. whether imported file was other than csv.
Model
class EmpAttendance < ActiveRecord::Base
attr_accessible :emp_id,:in_time,:out_time,:date,:status
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
@emp_attendance = EmpAttendance.find_by_emp_id_and_date(row['emp_id'],row['date']) || EmpAttendance.new
@emp_attendance.emp_id = row['emp_id']
@emp_attendance.in_time = row['in_time']
@emp_attendance.out_time = row['out_time']
@emp_attendance.status = row['status']
@emp_attendance.date = row['date']
@emp_attendance.save!
end
end
end
Controller
def import
if params[:file].present?
EmpAttendance.import(params[:file])
flash[:notice] = "Sucessfully Created."
redirect_to emp_attendances_path
else
flash[:error] = "No File Chosen"
redirect_to emp_attendances_path
end
end
View (Index.html.erb)
<div class='row-fluid clear'>
<div class='box gradient'>
<div class='title'>
<h3 style='margin-left:1em'>Add Driver Details</h3>
</div>
<div class='content'>
<% if flash[:notice].present? %>
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">×</button>
<%= flash[:notice] %>
</div>
<% end %>
<% if flash[:error].present? %>
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
<%= flash[:error] %>
</div>
<% end %>
<div>
<h3>Employee Attendance</h3>
<p>
</div>
<%= form_tag import_emp_attendances_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import", :class => 'btn btn-primary' %>
<% end %>
</div>
</div>
</div>
Please Help me..
The API Docs mentions the accept option:
file_field_tag :file, accept: 'text/csv'
:accept- If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
When I do csv imports, I do two things:
put the data-rows into intermediate hash-objects. Then I check basic things like that nr of columns is big enough. Also this decouples the csv-format from the format in the database.
insert all data in one transaction. When an object does not validate, nothing is imported, and there is a clear state. The user is not left with half imported data. writing many objects in one transactions also tend to be faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With