Action Policy

Action Policy logo


Action Policy relies on resource-specific policy classes (just like Pundit).

First, add an application-specific ApplicationPolicy with some global configuration to inherit from:

class ApplicationPolicy < ActionPolicy::Base

This may be done with the rails generate action_policy:install generator.

Then, write a policy for a resource. For example:

class PostPolicy < ApplicationPolicy
  # everyone can see any post
  def show?

  def update?
    # `user` is a performing subject,
    # `record` is a target object (post we want to update)
    user.admin? || ( == record.user_id)

This may be done with the rails generate action_policy:policy Post generator.

Now you can easily add authorization to your Rails controller:

class PostsController < ApplicationController
  def update
    @post = Post.find(params[:id])
    authorize! @post

    if @post.update(post_params)
      redirect_to @post
      render :edit

When the authorization is successful (i.e., the corresponding rule returns true), nothing happens, but in case of authorization failure ActionPolicy::Unauthorized an error is raised.

There is also an allowed_to? method which returns true or false, and could be used in views:

<% @posts.each do |post| %>
  <li><%= post.title %>
    <% if allowed_to?(:edit?, post) %>
      <%= link_to post, "Edit">
    <% end %>
<% end %>

Read more in the Documentation.


Further reading

In the same orbit

Explore more open source projects

Contact us

We’d love to hear from you! We’re not really all that evil, and we love discussing potential projects, intriguing ideas, and new opportunities. Complete the form below or drop us a line at Alternatively, schedule a Calendly appointment with us right now!

Martians at a glance
years in business

A product development consultancy that works with startups and established businesses, while also creating open source-based products and services