Installing Action Policy
Action Policy is already included in our application’s dependencies. Now we need to set up the base policy class.
The Installation Generator
In a real Rails project, you would run:
$ bin/rails generate action_policy:installThis creates - the base class that all your policies will inherit from.
Examine the ApplicationPolicy
Open in the editor:
# frozen_string_literal: true
# Base class for application policiesclass ApplicationPolicy < ActionPolicy::Base # Configure additional authorization contexts here # (`user` is added by default). # # authorize :account, optional: true # # Read more about authorization context: https://actionpolicy.evilmartians.io/#/authorization_context
private
# Define shared methods useful for most policies. # For example: # # def owner? # record.user_id == user.id # endendKey Points
1. Inherits from ActionPolicy::Base
ApplicationPolicy inherits from ActionPolicy::Base, which provides all the core functionality:
- Policy rule definitions
- Authorization context (the
userobject) - Pre-checks, aliases, and other features
2. Central Configuration
This class is the perfect place to:
- Add shared authorization contexts (like
accountororganization) - Define helper methods used across multiple policies
- Configure default behaviors
3. Convention
All your resource policies will inherit from this class:
class ProductPolicy < ApplicationPolicy # Policy rules hereend
class UserPolicy < ApplicationPolicy # Policy rules hereendWhat’s Next?
Now that we have the base policy class, let’s create our first actual policy for the Product model!
Files
Preparing Environment
- Preparing Ruby runtime
- Prepare development database