Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rescue from ActiveRecord::RecordNotFound in Rails

A user can only edit its own post, so I use the following to check if a user can enter the edit form:

  def edit     @post = Load.find(:first, :conditions => { :user_id => session[:user_id], :id => params[:id]})   rescue ActiveRecord::RecordNotFound     flash[:notice] = "Wrong post it"     redirect_to :action => 'index'   end 

But it is not working, any ideas what I am doing wrong?

like image 225
Adnan Avatar asked Feb 25 '10 18:02

Adnan


1 Answers

If you want to use the rescue statement you need to use find() in a way it raises exceptions, that is, passing the id you want to find.

def edit   @post = Load.scoped_by_user_id(session[:user_id]).find(params[:id]) rescue ActiveRecord::RecordNotFound   flash[:notice] = "Wrong post it"   redirect_to :action => 'index' end 
like image 187
Simone Carletti Avatar answered Sep 21 '22 20:09

Simone Carletti