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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 560
    Comment on it

    For an application we need some authorization method, Policies in rails is one of them.
    There is one library Pundit used for authorization.
    Pundit gem uses object oriented design and Ruby classes.

    To start with add this gems into your Gemfile and run bundle install:

    gem "pundit"

     

    Another method to set up an application policy using generator is :

    rails g pundit:install

    It will create a app/policies/ directory. After this restart the server so that it will pick up classes in the pp/policies/ directory.

    Ones you have generated your application policy after that restart the Rails server so that Rails can pick up any classes in the app/policies directory.

    Now create a policy class in app/policies/post_policy.rb

    class PostPolicy < ApplicationPolicy
      def destroy?
        user.admin?
      end
    end


    Inside the controller we need to check our rule:

    class PostController < ApplicationController
    
        def destroy
          authorize @post
          @post.destroy
    
          redirect_to posts_url, notice: 'Post was successfully destroyed.'
        end
    end

 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: