Checking if ActiveRecord find returns a result

后端 未结 7 1498
孤独总比滥情好
孤独总比滥情好 2021-02-07 08:03

I\'m trying to check if a find method returns a result. My find method is the following:

post = Post.find(:all, :conditions => { :url => params[\'url\'] },         


        
7条回答
  •  执念已碎
    2021-02-07 08:21

    Use the BANG! version of the find_by_url method to get it to raise an exception of it could not be found and then rescue it later on in that same method/action.

    def show
      Post.find_by_url!(params[:url])
      rescue ActiveRecord::RecordNotFound
        flash[:notice] = "The URL you were looking for could not be found."
        redirect_to root_path
      end
    end
    

    If you didn't raise an exception here I believe that Rails would show the public/404.html page.

提交回复
热议问题