2012-02-23 29 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 
相關問題