require 'csv'
class Product < ActiveRecord::Base
has_attached_file :photo, :styles => { :small => "150*150>" }
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
product = find_by_id(row["id"]) || new
product.attributes = row.to_hash.slice(*accessible_attributes)
product.save!
end
end
end
class ProductsController < ApplicationController
def import
Product.import(params[:file])
redirect_to root_url, notice: "Products imported."
end
end
答案 0 :(得分:1)
可能params [:file]为nil,因此这行失败了:
CSV.foreach(file.path, headers: true) do |row|