Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling ActiveRecord::RecordNotFound in Ruby on Rails

In my edit action, I have

@item = current_user.shop.items.find(params[:id])

So that the user can only edit items that belong to their shop. If they try to edit an item that does not belong to their shop, then they get an ActiveRecord::RecordNotFound error.

What is the best way of handling this error in situations like this? should i raise an exception? should i redirect somewhere and set the flash (if so, how do i do that), should i just leave it as is? Any advice is appreciated.

Thanks

like image 234
pingu Avatar asked Jul 25 '11 10:07

pingu


1 Answers

Add something like the following to your controller:

rescue_from ActiveRecord::RecordNotFound do
  flash[:notice] = 'The object you tried to access does not exist'
  render :not_found   # or e.g. redirect_to :action => :index
end
like image 198
Koraktor Avatar answered Nov 15 '22 09:11

Koraktor