【问题标题】:Create Pundit Policies to API controller methods为 API 控制器方法创建 Pundit 策略
【发布时间】:2018-01-17 22:30:49
【问题描述】:

如何使用Pundit gem为API控制器创建Policies

Api 控制器路径:/app/controllers/api/posts_controller.rb

#posts_controller.rb

class Api::PostsController < ApplicationController

  def create
  ......
  end


  def update
  ......
  end

  def delete
  ......
  end

end

我有相同的Controller 和对应的Model

控制器路径:/controllers/posts_controller.rb

#posts_controller.rb

class PostsController < ApplicationController

  def create
  ......
  end


  def update
  ......
  end

  def delete
  ......
  end

end

我已经为posts controller 创建了策略。如何为 API 的 Controller 创建相同的内容

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-5 pundit


    【解决方案1】:

    Pundit 是基于资源的,而不是基于控制器的。当您调用 authorize 并向其传递资源时,Pundit 关心操作名称和资源类型,但不关心控制器名称。

    不管你是否从 Api::PostsController 调用:

    # /app/controllers/api/posts_controller.rb
    
    class Api::PostsController < ApplicationController
    
      def create
        @post = Post.find(params[:post_id])
        authorize @post
      end
    end
    

    或来自您原来的 PostsController:

    # /app/controllers/posts_controller.rb
    
    class PostsController < ApplicationController
    
      def create
        @post = Post.find(params[:post_id])
        authorize @post
      end
    end
    

    只要@postPost类的成员,你就可以从父或子的控制器或完全不相关的控制器调用authorize @post,没关系。在所有情况下,Pundit 都会在 app/policies/post_policy 中查找名为 create? 的方法:

    # app/policies/post_policy.rb
    
    class PostPolicy < ApplicationPolicy
    
      attr_reader :user, :post
    
      def initialize(user, post)
        @user = user
        @post = post
      end
    
      def create?
        user.present?
      end
    end
    

    【讨论】:

    • 正是我想要的.. Tnx
    猜你喜欢
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 2023-01-27
    相关资源
    最近更新 更多