简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM