Ruby on rails 如何在rails 4中验证.csv文件

Ruby on rails 如何在rails 4中验证.csv文件,ruby-on-rails,csv,Ruby On Rails,Csv,我使用的是rails 4。我有员工考勤模型。因为我必须单独上传.csv文件。它不允许任何其他格式。那么,如何验证文件格式。导入的文件是否不是csv 模型 视图(Index.html.erb) 添加驱动程序详细信息 &时代; &时代; 员工出勤率 “btn btn主节点”%> 请帮帮我。提到了接受选项: file_field_tag :file, accept: 'text/csv' :接受-如果设置为一种或多种mime类型,则用户在选择文件时会被建议使用过滤器。您仍然需要设置模型验证 当

我使用的是rails 4。我有员工考勤模型。因为我必须单独上传.csv文件。它不允许任何其他格式。那么,如何验证文件格式。导入的文件是否不是csv

模型

视图(Index.html.erb)


添加驱动程序详细信息
&时代;
&时代;
员工出勤率

“btn btn主节点”%>
请帮帮我。

提到了
接受
选项:

file_field_tag :file, accept: 'text/csv'
:接受
-如果设置为一种或多种mime类型,则用户在选择文件时会被建议使用过滤器。您仍然需要设置模型验证


当我进行csv导入时,我会做两件事:

  • 将数据行放入中间哈希对象中。然后我检查基本情况,比如列的nr是否足够大。此外,这还将csv格式与数据库中的格式分离

  • 在一个事务中插入所有数据。当对象未验证时,不会导入任何内容,并且存在清除状态。用户不会留下一半导入的数据。在一个事务中写入多个对象也会更快


  • 这是可行的,但需要正确添加格式-accept:“.csv”Sartaj Singh的评论是可行的,这个解决方案对我不起作用。是因为我的Ubuntu测试环境,还是我需要在rails中声明mimetype?
    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
    
    <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">&times;</button>
            <%= flash[:notice] %>
        </div>
    <% end %>
    <% if flash[:error].present? %>
    
        <div class="alert alert-danger">
            <button type="button" class="close" data-dismiss="alert">&times;</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>                   
    
    file_field_tag :file, accept: 'text/csv'