我正在使用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>
请帮助我..
答案 0 :(得分:6)
API Docs提及accept
选项:
file_field_tag :file, accept: 'text/csv'
:accept
- 如果设置为一个或多个mime-types,则在选择文件时会建议用户使用过滤器。您仍然需要设置模型验证。
答案 1 :(得分:2)
当我进行csv导入时,我会做两件事:
将数据行放入中间哈希对象中。然后我检查基本的东西,比如列的数量足够大。这也将csv格式与数据库中的格式分离。
在一个交易中插入所有数据。当对象未验证时,不会导入任何内容,并且存在明确的状态。用户不会留下一半导入的数据。在一次交易中写很多对象也会更快。