Rails 5 - how to use Pundit

I had a long break with my 2 year efforts in trying to learn how to use pundit in my rails application. I am back and trying to learn how to use pundit.

I made a brand new 5 rails application and installed pundit.

I have a user resource, application policy, and user policy. Everyone has:

User Controller:

def index
    # @users = User.all
    @users = policy_scope(User)
  end

Application policy

class ApplicationPolicy
  attr_reader :user, :record

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

  def index?
    true
  end

  def show?
    scope.where(:id => record.id).exists?
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

  def scope
    Pundit.policy_scope!(user, record.class)
  end

  class Scope
    attr_reader :user, :scope

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

    def resolve
      scope
    end
  end
end

User policy

class UserPolicy < ApplicationPolicy
  class Scope < Scope
    def resolve
      scope.where(user: user)
    end
  end


end

Then in my user pointer, I try to follow the instructions in the gem pundit docs by doing:

<% policy_scope(@users).each do |user| %>

I get this error:

PG::UndefinedColumn: ERROR:  column users.user does not exist
LINE 1: SELECT "users".* FROM "users" WHERE "users"."user" = '566119...
                                            ^
: SELECT "users".* FROM "users" WHERE "users"."user" = '566119d2-54d8-4ab2-b7c5-f17c80b517f3' AND "users"."user" = '566119d2-54d8-4ab2-b7c5-f17c80b517f3'

Can anyone see me getting the wrong start? I have not even tried to define my scope as I want, but at the moment it does not work.

+4
1
class UserPolicy < ApplicationPolicy
  class Scope < Scope
    def resolve
      scope.where(user: user)
    end
  end
end

scope.where User (user.where), .

- , .

, , , . :

scope.where(id: user.try(:id))

,

def index
  # @users = User.all
  @users = policy_scope(User)
end

.

 <% policy_scope(@users).each do |user| %>

. users.each do....

+1

Source: https://habr.com/ru/post/1656672/


All Articles