Posted By

wackimonki on 02/26/07


Tagged

rails rubyonrails


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

webstic


Catching Error to be Displayed on Redirected Page


 / Published in: Ruby
 

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.

  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
  16.  
  17. # RHTML code
  18. <% if flash[:notice] -%>
  19. <div id="notice"><%= flash[:notice] %></div>
  20. <% end -%>

Report this snippet  

You need to login to post a comment.