Rails权限控制 #
一、授权概述 #
1.1 授权方式 #
| 方式 | 说明 |
|---|---|
| Pundit | 基于策略的授权 |
| CanCanCan | 基于能力的授权 |
二、Pundit #
2.1 安装 #
ruby
gem 'pundit'
2.2 创建策略 #
ruby
# app/policies/article_policy.rb
class ArticlePolicy < ApplicationPolicy
def index?
true
end
def show?
true
end
def create?
user.present?
end
def update?
user.admin? || record.user_id == user.id
end
def destroy?
user.admin?
end
end
2.3 使用策略 #
ruby
class ArticlesController < ApplicationController
def update
@article = Article.find(params[:id])
authorize @article
end
end
三、CanCanCan #
3.1 定义能力 #
ruby
class Ability
include CanCan::Ability
def initialize(user)
can :read, Article
can :create, Article if user.present?
can :manage, Article, user_id: user.id
can :manage, :all if user.admin?
end
end
3.2 使用能力 #
ruby
class ArticlesController < ApplicationController
def update
@article = Article.find(params[:id])
authorize! :update, @article
end
end
四、总结 #
4.1 核心要点 #
| 要点 | 说明 |
|---|---|
| Pundit | 策略类授权 |
| CanCanCan | 能力类授权 |
| authorize | 授权检查 |
4.2 下一步 #
现在你已经掌握了权限控制,接下来让我们学习 API模式,深入了解Rails的API开发!
最后更新:2026-03-28