rescue from ActiveRecord::RecordNotFound in Rails

前端 未结 3 1475
日久生厌
日久生厌 2020-12-13 04:08

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 =&         


        
相关标签:
3条回答
  • 2020-12-13 04:16

    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
    
    0 讨论(0)
  • 2020-12-13 04:34

    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
    
    0 讨论(0)
  • 2020-12-13 04:37

    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
    
    0 讨论(0)
提交回复
热议问题