Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • RecordNotFoundException

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 280
    Comment on it
    class ApplicationController < ActionController::Base
     protect_from_forgery with: :exception
     before_action :configure_permitted_parameters, if: :devise_controller?
     protected
     def configure_permitted_parameters
        devise_parameter_sanitizer.for(:sign_up)<<[:first_name,:last_name,:terms_and_conditions]
     end
     private
      def current_cart
       Cart.find(session[:cart_id])
       rescue ActiveRecord::RecordNotFound
       cart = Cart.create
       session[:cart_id] = cart.id
       cart
      end
    end

    RecordNotFound:

    It the exception class defined in the

    ~/.rvm/gems/ruby-version/gems/activerecord-version/lib/active_record/errors.rb

    This RecordNotFound Exception is thrown when Active Record cannot find record by given id or set ids.

    RecordNotFound class is inherited from ActiveRecordError which is inherited from StandardError class which is subclass of Exception class.Thus Exception class is the super class of all the classes.

    If we are using the rescue statement we need to use find() in such a way tha it raises an exception , that is , passing the id you want to find.

    private
    def current_cart
     Cart.find(session[:cart_id])
     rescue ActiveRecord::RecordNotFound
     cart = Cart.create
     session[:cart_id] = cart.id
     cart
     end

    Cart.find method will find the cart_id temporarily present in the session , if the cart _id is present in the session the current_cart method simply returns the whole object of the cart otherwise it will throw an RecordNotFound Exception which means that the cart_id is not present in the session , then it will create a cart and  store it in the session.Lastly it returns the object of the cart.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: