Catching Error to be Displayed on Redirected Page

/ Published in: Ruby
Save to your folder(s)

Catches an exception error, uses a technique called flash to display error on another page.

The Ruby on Rails code needs to be in a controller.

The rhtml code needs to be in the index layout.

Copy this code and paste it in your HTML
  1. def add_to_cart
  2. begin
  3. product = Product.find(params[:id])
  4. # if can not find product id, catch exception, raise error to be
  5. # displayed on 'index' page
  6. rescue ActiveRecord::RecordNotFound
  7. logger.error("Atempt to access invalid product #{params[:id]}")
  8. flash[:notice] = "invalid product"
  9. redirect_to :action => :index
  10. else
  11. # if can find product id, continue to add product to cart
  12. @cart = find_cart
  13. @cart.add_product(product)
  14. end
  15. end
  17. # RHTML code
  18. <% if flash[:notice] -%>
  19. <div id="notice"><%= flash[:notice] %></div>
  20. <% end -%>

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.