CSV上传期间未应用验证

时间:2015-09-01 18:55:09

标签: ruby-on-rails validation csv ruby-on-rails-4

我的模型有以下内容:

validates_uniqueness_of :batch, :scope => :projectid

AND

 def self.import(csv_file)
    CSV.foreach(csv_file, headers: true) do |row|
      Order.create! row.to_hash
    end
  end

无论验证如何,csv都会上传并放置在数据库中(我故意尝试插入一条违反该验证的记录)。我不确定为什么允许它在上传时违反该验证。

控制器:

  def import
    Order.import(params[:csv_file].tempfile)
    redirect_to orders_path, :notice => "Orders imported"
  end

形式:

<%= form_tag import_orders_path, multipart: true do %>
  <div class="controls">
  <%= file_field_tag :csv_file, accept: 'csv', :class => 'btn btn-xs btn-info' %>    
  <%= submit_tag "Upload Orders", :class => 'btn btn-xs btn-success' %>
  </div>

1 个答案:

答案 0 :(得分:0)

def self.import(csv_file)
    order = Order.new
    if order.valid? == false
      nil
    else
      CSV.foreach(csv_file, headers: true) do |row|
        Order.create! row.to_hash
      end
    end
  end