Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use namespace in gem Pundit

I have 2 controller, 1 for user and 1 for admin.

controllers/articles_controller.rb

class ArticlesController < ActionController::Base
  ...
  def show 
    @article = Article.find(parmas[:id])
    authorize @article
  end
  ...
end

controllers/admin/articles_controller.rb

class Admin::ArticlesController < AdminController
  ...
  def show 
    @article = Article.find(parmas[:id])
    authorize @article
  end
  ...
end

And i have 2 file policy policies/article_policy.rb

class ArticlePolicy
  extend ActiveSupport::Autoload
  autoload :Admin

  attr_reader :user, :record

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

  def show?
    # allow show for every user. 
    true 
  end  
end

And one file policies/admin/article_policy.rb

class Admin::ArticlePolicy

  attr_reader :user, :record

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

  def show?
    # only show if use have role manager 
    user.manager? 
  end  
end

but when i use a account user to show articles at /admin/articles/1/. It show normaly, Should is "Access denied".

How to fix this? (I use gem pundit 1.10).

like image 469
bav ko ten Avatar asked Dec 14 '22 06:12

bav ko ten


1 Answers

Use the authorize method to pass the namespace as a parameter.

class ArticlesController < ActionController::Base
  ...
  def show 
    @article = Article.find(parmas[:id])
    authorize [:admin, @article]
  end
  ...
end
like image 87
Alexander Rühle Avatar answered Dec 28 '22 23:12

Alexander Rühle