views:

324

answers:

2

Hello,

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?

+4  A: 

Turns out you were using rescue and find(:first) incorrectly.

find :first returns nil if no record matches the conditions. It doesn't raise ActiveRecord::RecordNotFound

try

def edit
  @post = Load.find(:first, :conditions => { :user_id => session[:user_id], :id => params[:id]})
  if @post.nil?
    flash[:notice] = "Wrong post it"
    redirect_to :action => 'index'
  end
end
EmFi
I am getting "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id"
Adnan
You were using rescue wrong, but the real problem is that find :first returns nil if no record is found. Solution updated to address the real root of your problem.
EmFi
+1  A: 

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
Simone Carletti
Thank you @Simone Carletti that is it.
Adnan