抢救活动记录:记录无效

Dee*_*gla 0 ruby-on-rails ruby-on-rails-3

这是我的代码.

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
Run Code Online (Sandbox Code Playgroud)

当我保存具有相同名称的重复模型时,会引发异常

ProductsController #import中的ActiveRecord :: RecordInvalid

Validation failed: Name has already been taken

Rails.root: /home/deepender/396-importing-csv-and-excel/store-before
Run Code Online (Sandbox Code Playgroud)

我正在使用救援操作仍然没有处理错误?任何我猜对错的猜测.

Cod*_*lan 5

几件事.你没有包装你validatesbegin/rescue块.所以你的模型应该只是:

class Product < ActiveRecord::Base
  attr_accessible :name, :price, :released_on
  validates :name, uniqueness: true
end
Run Code Online (Sandbox Code Playgroud)

它在控制器中执行验证并适当地处理它.示例控制器可能如下所示:

class ProductsController < ApplicationController
  def create
    @product = Product.new(params[:product])
    if @product.valid?
      @product.save
      flash[:notice] = "Product created!"
      redirect_to(@product) and return
    else
      render(:action => :new)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

然后在您的视图中,您可能会将实际错误呈现给用户:

# app/views/products/new.html.erb

<%= error_messages_for(@product) %>
.. rest of HTML here ..
Run Code Online (Sandbox Code Playgroud)

error_messages_for 默认情况下不再包含在Rails中,而是在gem中 dynamic_form

有关显示错误的一般方法,请参阅此Rails指南:

http://guides.rubyonrails.org/active_record_validations.html#displaying-validation-errors-in-views