使用Raise ActiveRecord :: Rollback重定向?

时间:2011-12-14 12:31:26

标签: ruby-on-rails ruby ruby-on-rails-3

我无法正确重定向,它一直在向我ActiveRecord::RecordInvalid投掷,但它应该将:back重定向到原始页面。

def create_multiple
   Product.transaction do 
     begin
       @products = current_user.products.create!(params[:products].map { |_k, p| p.merge params[:product] })
         redirect_to :back, :notice => "Success!"
       rescue ActiveRecord::Rollback
         redirect_to :back, :notice => "An error occured, please try again."
       end
     end
   end
end

如何让它重定向?

1 个答案:

答案 0 :(得分:4)

如果你想捕获ActiveRecord :: RecordInvalid异常,那你为什么不抢救那个而不是ActiveRecord :: Rollback?

def create_multiple
  Product.transaction do
    @products = current_user.products.create! ...
  end
  notice = "Success!"
rescue ActiveRecord::RecordInvalid
  notice = "An error occurred, please try again"
ensure
  redirect_to :back, :notice => notice
end

我会像上面这样编写这个函数。