我正在使用 rails 4。我有员工考勤模型。我必须单独上传 .csv 文件。它不允许任何其他格式。那么,如何验证文件格式。导入的文件是否不是 csv。
模型
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
控制器
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
查看 (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>
请帮我..