You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Action Policy relies on resource-specific policy classes (just like Pundit).
First, add an application-specific ApplicationPolicy with some global configuration to inherit from:
classApplicationPolicy < ActionPolicy::Baseend
This may be done with rails generate action_policy:install generator.
Then write a policy for a resource. For example:
classPostPolicy < ApplicationPolicy# everyone can see any postdefshow?trueenddefupdate?# `user` is a performing subject,# `record` is a target object (post we want to update)user.admin? || (user.id == record.user_id)endend
This may be done with rails generate action_policy:policy Post generator.
You can also use rails generate action_policy:policy Post --parent=BasePolicy to make the generated policy inherits
from BasePolicy.
Now you can easily add authorization to your Rails* controller:
* See Non-Rails Usage on how to add authorize! to any Ruby project.
When authorization is successful (i.e., the corresponding rule returns true), nothing happens, but in case of authorization failure ActionPolicy::Unauthorized error is raised.
There is also an allowed_to? method which returns true or false, and could be used, in views, for example:
<% @posts.each do |post| %><li><%=post.title%><%ifallowed_to?(:edit?,post)%><%=link_topost,"Edit">
<% end%></li><%end%>