我的用户目前有两种类型的角色[:member , :admin]
,成员可以CRUD创建大多数帖子。 :admin可以在任何后期进行CRUD。现在我试图创建一个只能查看和更新所有帖子的主持人。我已将:moderator
添加到enum role:
。我也包括在内
before_action :moderator_user, except: [:index, :show]
和
def authorize_user
unless current_user.admin?
flash[:alert] = "You must be an admin to do that."
redirect_to topics_path
end
end
def moderator_user
unless current_user.moderator?
flash[:alert] = "You must be an moderator to do that."
redirect_to topics_path
end
end
但似乎干扰了我的before_action :authorize_user, except: [:index, :show]
因为它导致我的rspec测试失败。
我试图找出如何创建一个主持人角色,该角色将在成员和管理员之间但不影响任何一个。
helper.rb:
def user_is_authorized_for_topics?
current_user && current_user.admin?
end
def user_is_moderator_for_topics?
current_user && current_user.moderator?
end
答案 0 :(得分:0)
这是其中一个授权宝石的完美案例 - Pundit
或CanCanCan
。对于以用户为中心的实施,CanCanCan
可能是最好的......
#Gemfile
gem 'cancancan', '~> 1.13'
#app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in) #-> looks for "current_user"
case true
when user.admin?
can :manage, Post #-> CRUD all
when user.moderator?
can [:read, :update], Post #-> update/read posts
when user.member?
can :manage, Post, user_id: user.id #-> CRUD their posts
end
end
end
以上功能可让您在控制器和电脑中使用can?
and authorize
methods。的观点:
#app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
load_and_authorize_resource
end
#app/views/articles/index.html.erb
<% @articles.each do |article| %>
<% if can? :update, article %>
<%= link_to "Edit", edit_article_path(article) %>
<% end %>
<% end %>
以上情况应该适合你。
load_and_authorize_resource
过滤器应为您提供范围数据:
从1.4开始,索引操作将使用accessible_by加载集合资源。
def index # @products automatically set to Product.accessible_by(current_ability) end
-
有一个很棒的Railscast about this here。 Railscasts的创建者在被烧毁之前创作了CanCan
,所以一个新的社区用CanCanCan
开始了它。