简体   繁体   中英

Implementing a policy class using Pundit - Rails

I writing a class called AdminPolicy This class is basically trying to say whether or not a user is an admin... Right now I pass in the current_user and the current_account . I basically have a join to table between user and account and that has the admin attribute on it. Everything seems to be working fine except for this error that I'm getting undefined local variable or method 'admin_policy' . Here is my code, I can't seem to figure out what is wrong?

admin policy class

class AdminPolicy < ApplicationPolicy
  attr_reader :user, :account

  def initialize(user, account)
    @user = user
    @account = account
  end

  def allow_access?(user, account)
    membership = account.membership_for?(user)

    if membership.admin
      true
    else
      false
    end
  end
end

pages controller

def admin_policy
  @admin_policy ||= AdminPolicy.new(current_user, current_account)
end

dashboard.html.erb

<% if admin_policy.allow_access?(current_user, current_account) %>
  <div class="admin-dashboard">
    <%= render partial: "admin_dashboard" %>
  </div>
<% else %>
  <div class="worker-dashboard">
    <%= render partial: "worker_dashboard" %>
  </div>
<% end %>

Error

在此处输入图片说明

So its saying that admin_policy is undefined.. Any idea why this would be?

First, allow_access? doesn't need to receive parameters, so your policy should be

class AdminPolicy < ApplicationPolicy
  attr_reader :user, :account

  def initialize(user, account)
    @user = user
    @account = account
  end

  def allow_access?
    membership = account.membership_for?(user)

    if membership.admin
      true
    else
      false
    end
  end
end

In your views, you can call it in this way (this is not the only way to do it)

<% if policy(Admin).allow_access? %>
  <div class="admin-dashboard">
    <%= render partial: "admin_dashboard" %>
  </div>
<% else %>
  <div class="worker-dashboard">
    <%= render partial: "worker_dashboard" %>
  </div>
<% end %>

Be sure to read carefully the documentation .

Heads up!

If you are inheriting from ApplicationPolicy you don't need to include attr_reader and ìnitialize method because both are defined by default in the ÀpplicationPolicy

Try this

<% if @admin_policy.allow_access?(current_user, current_account) %>

Hope this will helping you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM