1
votes

I'm trying to figure out how to use pundit with my namespaced resources.

I've read lots of SO posts from others saying they have problems with this, but those predate discussions on the pundit gem issue tracker. The issue tracker isn't clear about what the solution is - so I'm stuck.

I have folder called Stance, which is a namespace for nested resources, one of which is called overview.

The model.rb file is called:

class Stance::Overview < ApplicationRecord

The controller is called:

class Stance::OverviewsController < ApplicationController

The table in the db is called:

create_table "stance_overviews", force: :cascade do |t|

In my app/policies folder, I've tried various ways of making a policy, with various attempts at then referencing the policy in the views. I can't find a way that works.

I've tried making a folder called Stance with a file called overview_policy.rb, with:

class Stance::OverviewPolicy < ApplicationPolicy

In my organisation view (which has one stance::overview), i define a local variable):

<% if current_user.organisation_id != @organisation.id %>

    <%= render 'stance/overviews/internal', overview: @organisation.overview %>
<% else %>
    <%= render 'stance/overviews/external', overview: @organisation.overview  %>
<% end %>   

Then in the view, I'm trying:

<% if policy(overview).show? %> 

<p><%= overview.explanation %></p>

<% end %>

I can't find a variation on this that works. Everything I've tried is a guess based on the SO posts, most of which predate the conversations on the pundit issue tracker.

I don't get an error message, but the content doesnt render when it should.

Can anyone see what I need to do to be able to use pundit with namespaced resources?

1
Do you have the stance folder for the policy file named Stance or stance? I think it needs to be all lower case. We have a similar setup with one of our models and it's working fine. The only authorization is in the controller though.Scott
I have a lower case folder called 'stance' inside my policies folder. How do you name your class in the policy? I am doing this: class Stance::OverviewPolicy < ApplicationPolicyMel
That is exactly how I have mine setup. What error do you get?Scott

1 Answers

0
votes

when I meet the namespace problem, I use Pundit.policy().

For your class, I think should be use Pundit.policy(current_user,[:stance, :overview]).show? in the view and use authorize [:stance, @overview] in the controller.

the Pundit.policy(current_user,[:stance, :overview]).show? will find show? in app/policies/stance/overview_policy.rb.

if you write authorize [:stance, @overview] on show in your controller, it will find show? in app/policies/stance/overview_policy.rb.