如何在销毁操作上显示错误消息,因为它重定向到索引操作?

时间:2012-02-23 20:09:43

标签: ruby-on-rails ruby-on-rails-3 error-handling destroy

在我的模型中:

before_destroy :ensure_not_referenced_by_any_shopping_cart_item

def ensure_not_referenced_by_any_shopping_cart_item
  unless shopping_cart_items.empty?
    errors.add(:base, "This item can't be deleted because it is present in a shopping cart")
    false
  end
end

当商品出现在购物车中时,它不会被销毁(这很好),如果我将其记录在操作中,我会看到错误。

def destroy
  @product = Beverage.find(params[:id])
  @product.destroy

  logger.debug "--- error: #{@product.errors.inspect}"

  respond_to do |format|
    format.html { redirect_to beverages_url }
    format.json { head :ok }
  end
end

..但是当redirect_to发生时,放弃了设置错误消息的实例变量,因此用户永远不会看到它。

如何将错误消息保留到下一个操作,以便可以在其视图中显示?

谢谢!

4 个答案:

答案 0 :(得分:3)

我建议使用flash消息来传递错误信息。

respond_to do |format|
  format.html { redirect_to beverages_url, :alert => "An Error Occurred! #{@products.errors[:base].to_s}"
  format.json { head :ok }
end

这样的效果。这就是我在自己的应用程序中处理类似问题的方式,但这取决于您要向用户显示的信息的详细信息。

答案 1 :(得分:1)

您需要将错误放入闪存中。大致像

的东西
def destroy
  @product = Beverage.find(params[:id])
  if @product.destroy
    message = "Product destroyed successfully"
  else
    message = "Product could not be destroyed"
  end


  respond_to do |format|
    format.html { redirect_to beverages_url, :notice => message }
    format.json { head :ok }
  end
end

请注意,您还需要在application.html.erb文件中打印消息。

答案 2 :(得分:0)

您可以使用两条消息执行此操作,一条状态为OK,另一条为NO OK( unprocessable_entity ,例如here's more)。

def destroy
  @product = Beverage.find(params[:id])


  respond_to do |format|
    if @product.destroy
     format.html { redirect_to beverages_url, notice: "Product destroyed successfully", status: :ok}
     format.json { head :ok, status: :ok}
    else
      format.html { redirect_to beverages_url, alert: "Product could not be destroyed", status: :unprocessable_entity}
      format.json {head :no_content, status: :unprocessable_entity }
    end
  end
end

答案 3 :(得分:0)

在Rails 4中,你可以这样做

def destroy
  @product = Beverage.find(params[:id])

  respond_to do |format|
    if @product.destroy
      format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
      format.json { head :ok }
    else
      format.html { render :show }
      format.json { render json: @product.errors, status: :unprocessable_entity }
    end
  end
end