我正在使用 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
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
查看 (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>
请帮我..
最佳答案
API Docs提到了 accept
选项:
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.
关于ruby-on-rails - 如何在 rails 4 中验证 .csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19563988/