pundit: Unable to access namespaced policy in view

Given a TagsController and an Admin::TagsController each with a corresponding policy, how does one access the admin policy from a view? I’ve got a global nav link I’d like to only expose to admins.

policy(Tag).index? references the non-Admin namespace policy

I assumed something like this would work: policy(Admin::Tag).index? However, Admin::Tag is not defined and thus, it throws an error.

Ideally, I’d do something like so: policy(Tag, namespace: 'admin').index?

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 30 (5 by maintainers)

Commits related to this issue

Most upvoted comments

My 2 cents are that I’m convinced that authorization should be tied to controllers and not models. To that end, namespacing would be nice.

However if the Pundit philosophy is of a model based authorization, then it’s almost definitely a bad idea to add namespacing.

As a potential work around for those trying to get namespaced policies in views, you can do something like:

If you have a Foo::BarPolicy and you’re trying to access the show? method

policy('Foo::Bar'.to_sym).show?

You can even wrap this into a helper for easier use

module ApplicationHelper
  def foo_policy(policy_symbol)
    policy_class_name = policy_symbol.to_s.classify
    policy("Foo::#{policy_class_name}".to_sym)
  end
end

Then used in a view like:

foo_policy(:bar).show?