2012-02-23 51 views
0

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

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发生被放弃的实例变量,所以用户永远看不到它。

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

谢谢!

回答

3

我会建议使用闪光信息来中继错误信息。

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

感谢您在回答中包含'#{@ products.errors [:base] .to_s}':) – user664833 2012-02-23 22:02:17

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文件中打印出的消息。

+0

谢谢,@cailinanne,无论你和@Justin赫里克的答案是正确的,但我接受了他的答案,因为他进来越快。尽管如此,我仍然将你的标记标记为“有用”。:)另外,感谢关​​于'application.html.erb'的提示! – user664833 2012-02-23 22:00:41

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 
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 
相关问题