开发者

Best Method Cancan With Many Roles

开发者 https://www.devze.com 2023-03-14 11:43 出处:网络
Looking for some general advice and tips about using cancan on our latest rails3 project. We\'re building an ordering system which we use internally and provide restricted client access. These includ

Looking for some general advice and tips about using cancan on our latest rails3 project.

We're building an ordering system which we use internally and provide restricted client access. These include:

Superadmin
Superaccounts
Supertechs 
Clientadmin
Clientaccounts
Clienttechs

In our views, we've previously us开发者_Python百科ed a combination of:

<% if can? :manage User %>

And

<% if current_user.role_ids.include?(2) %>

I suspect the latter is bad practice and would appreciate finding out how to best achieve the same method.

We're also a little confused about how to deal with many roles.

What's the best way to provide access to multiple user groups - i.e. superadmin and supertechs?


I think the best option to replace

<% if current_user.role_ids.include?(2) %>

is to create a method for each role inside the model, for example:

class Company < ActiveRecord::Base
  .
  . 
  def super_admin?
    self.role_ids.include?(2)
  end
  .
  .

This way you will remove the query logic from the views and keep it on the controller and you will also be able access the roles by simply doing:

<% if current_user.super_admin? %>

Hope it helps :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号