How do I use the default application / policies / application_policy.rb?
When I create a new scaffold, I would like to use it as the default for the pundit configuration available in app/policies/application_policy.rb
. Without creation, model_name_policy.rb
I always get errors unable to find policy
.
How can I use the default values ββwhen I have not configured rules for a specific model?
source to share
The easiest way to do this is probably to save yourself from Pundit::NotDefinedError
being raised Pundit::PolicyFinder#policy!
.
Given your default policy:
# app/policies/application_policy.rb:
ApplicationPolicy = Struct.new :user, :record do
def index?
true
end
def show?
true
end
# ... other sensible defaults
end
Assuming you are using this in your Rails controller:
# app/controllers/application_controller.rb:
class ApplicationController
include Pundit
# ...
private
def policy(record)
super
rescue Pundit::NotDefinedError
ApplicationPolicy.new pundit_user, record
end
end
Disclaimer: I should also point out that creating implicit default policies is generally frowned upon . Except in the simplest cases, or with the most pessimistic defaults (all false), it's all too easy to avoid overly permissive politics.
source to share
I don't know a way without creating a policy for each model, but you can create a policy that inherits from your application policy. Yours ApplicationPolicy
might look something like this:
class ApplicationPolicy
def index?
true
end
def show?
true
end
... More actions ...
end
When you set up a new scaffold, simply add an empty policy that inherits your application policy:
class UserPolicy < ApplicationPolicy
end
Actions inherit from ApplicationPolicy
. You can always override the defaults if needed:
classUserPolicy < ApplicationPolicy
show?
@user.admin == true ? true : false
end
end
Hope this helps!
source to share