0

I am trying to figure out how to write pundit permissions in my Rails 4 app.

I have an article model, with an article policy. The article policy has:

class ArticlePolicy < ApplicationPolicy
    attr_reader :user, :scope

    def initialize(user, record, scope)
      @scope = scope
      super(user, record)
    end

    class Scope < Scope         
      def resolve
        if user == article.user
          scope.where(user_id: user_id)
        elsif approval_required?
          scope.where(article.state_machine.in_state?(:review)).(user.has_role?(:org_approver)) 
        else
          article.state_machine.in_state?(:publish)  
        end 
      end
    end 

    # TO DO - check if this is correct - I'm not sure.
    # I now think I don't need the index actions because I have changed the action in the articles controller to look for policy scope.
    # def index?  
    #   article.state_machine.in_state?(:publish)
    # end

    def article
      record
    end

The articles controller has:

def index
  @articles = policy_scope(Article)
  # query = params[:query].presence || "*"
  # @articles = Article.search(query)
end

I am following the pundit documents relating to scopes and trying to figure out why the index action shown in the policy documents isn't working for me. I have tried the following (as shown in the docs):

 <% policy_scope(@user.articles).sort_by(&:created_at).in_groups_of(2) do |group| %>

but I get this error:

undefined local variable or method `article' for #<ArticlePolicy::Scope:0x007fff08ae9f48>

Can anyone see where I've gone wrong?

I'm not sure that @user.articles is right. In my construct, articles belong to users, but in my index action, I want to show every user the articles that my scopes allow them to see.

BIlal Khan
  • 453
  • 3
  • 16
Mel
  • 2,481
  • 26
  • 113
  • 273

2 Answers2

0

You can try this in your action in controller.

@articles = policy_scope(Article).all

It will get all the articles. If you want to get the articles based on search params, you can try this.

@q = policy_scope(Article).search(params[:query])
@articles = @q.result
BIlal Khan
  • 453
  • 3
  • 16
0

I think you may need to explicitly set article as an accessor in the Scope class as the error indicates that it doesn't recognise 'article'. Try something like

attr_accessor :article

set it in an initialize method and you can probably do away with the article method.

def initialize(record)
  @article = record
end
margo
  • 2,927
  • 1
  • 14
  • 31
  • Hi @margo thanks for the suggestion. I tried this, but I still get the same error message as I showed above. – Mel Jul 19 '16 at 03:30