Adnan
Adnan

Reputation: 26350

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?

Upvotes: 48

Views: 68461

Answers (3)

Tim Baas
Tim Baas

Reputation: 6185

You can also use ActionController's rescue_from method. To do it for the whole application at once!

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

  def record_not_found
    render 'record_not_found' # Assuming you have a template named 'record_not_found'
  end
end

Upvotes: 53

Simone Carletti
Simone Carletti

Reputation: 176472

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

Upvotes: 72

EmFi
EmFi

Reputation: 23450

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

Upvotes: 8

Related Questions