Ruby on rails 为我的应用创建版主授权用户角色
目前,我的用户有两种类型的角色Ruby on rails 为我的应用创建版主授权用户角色,ruby-on-rails,rspec,roles,Ruby On Rails,Rspec,Roles,目前,我的用户有两种类型的角色[:member,:admin],成员可以对他们创建的大多数帖子进行CRUD:管理员可以在任何后期执行CRUD。现在我试图创建一个版主,只能查看和更新所有帖子。我已将:版主添加到我的枚举角色:。我还包括 在\u操作之前:版主\u用户,除了:[:索引,:显示]和 def authorize_user unless current_user.admin? flash[:alert] = "You must be an admin to do th
[:member,:admin]
,成员可以对他们创建的大多数帖子进行CRUD:管理员可以在任何后期执行CRUD。现在我试图创建一个版主,只能查看和更新所有帖子。我已将:版主添加到我的枚举角色:
。我还包括
在\u操作之前:版主\u用户,除了:[:索引,:显示]
和
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
但似乎在\u action:authorize\u user之前干扰了我的,除了:[: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
这是一个完美的案例,适用于授权宝石之一——或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
以上内容将使您能够在控制器和视图中使用:
#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 %>
--
有一个很大的问题。Railscasts的创建者在被烧毁之前编写了《CanCan》,因此一个新的社区采用了《CanCan》,这是授权宝石之一的完美案例——或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
以上内容将使您能够在控制器和视图中使用:
#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 %>
--
有一个很大的问题。Railscasts的创建者在被烧毁之前编写了CanCan
,因此一个新的社区采用了CanCanCan