这是我的代码。
class Product < ActiveRecord::Base
attr_accessible :name, :price, :released_on
begin
validates :name, uniqueness: true
rescue ActiveRecord::RecordInvalid => e
render( inline: "RESCUED ActiveRecord::RecordInvalid" )
return
end
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << column_names
all.each do |product|
csv << product.attributes.values_at(*column_names)
end
end
end
def self.import(file)
CSV.foreach(file.path , headers:true) do |row|
Product.create! row.to_hash # If we want to add a new item
end
end
end
当我保存具有相同名称的重复模型时,会引发异常
ProductsController#import 中的 ActiveRecord::RecordInvalid
Validation failed: Name has already been taken
Rails.root: /home/deepender/396-importing-csv-and-excel/store-before
我正在使用救援操作仍然没有处理错误?任何猜测我错了。