LoginSignup
121
125

More than 5 years have passed since last update.

Cancanで管理者と一般ユーザを簡単にわける方法 - ユーザタイプごとの役割の設定(認可)

Posted at

CanCanを使ってみたのでメモ。
ユーザグループAとBとCそれぞれに対して出来るアクションを分けたいときに便利。
例えば、管理者と一般ユーザで分けるとか。

1. まずはAbilityクラスを作る

rails g cancan:ability

2. メイン設定

めちゃくちゃ簡単。誰が何をすることが出来るか(can)定義。

CRUD(:create, :read, :update, :delete)の操作それぞれ、またはそれら全てを意味する :manage に対して"can"を決めるだけ。

app/models/ability.rb
def initialize(user)
  user ||= User.new
  if user.type == 1
    can :manage, User
    can :manage, Product
  else                                                                                                                           
    can :read, User
    can :read, Product
  end
end

canの代わりに

cannot :delete, User

みたいに書くこともできます。

3. ラスト!

該当するコントローラに

app/controllers/user_controller.rb
load_and_authorize_resource

を追加したら完了!
これで、user.typeが1のユーザのみユーザ(User)や商品(Product)の追加が出来るようになりました。

もうひと押し

ヘルパー

このままだとuser.typeが1でないユーザに、行えないアクション(ユーザの追加など)のリンクを表示してしまうことになるので、

  • can?
  • cannot?

を使いましょう。

例えば、

app/views/users/index.html.erb
<% if can? :create, User %>
  <%= link_to 'New User', new_user_path %>
<% end %>

CanCan::AccessDenied のために

最後に、認可されてないアクションを行おうとした際の処理をを書いておく。

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_url, :alert => exception.message
  end
end

とりあえず

めちゃくちゃ簡単!

121
125
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
121
125