LoginSignup
2
0

More than 1 year has passed since last update.

cancancanでモデル名に紐づかない制御をする方法

Last updated at Posted at 2022-03-14

はじめに

権限制御のgemとして、cancancanがあると思います。
基本的な使い方はいろいろなところで記事になっていますが、「コントローラ名通りのモデルがないとき」の権限制御方法について記載します。

コントローラで次のように記載

class ProfilesController
  authorize_resource  class: :profile # ここではコントローラ名と同じprofileにしていますが、コントローラと名前を揃える必要もないです

  def new 
    ...
  end

  def edit
    ...
  end

end

シンボルの形で描くことで、モデルがなくても権限管理することができます。
あとは通常の使い方と同じで、abilityクラスで定義していきます。

class Ability
  include CanCan::Ability
  
  def initialize(user)
    if user.admin? # もしユーザーがadminなら全ての権限を付与
      can :manage, :profile
    elsif user.company? # もしユーザーがcompanyなら閲覧のみ可能
      can :read, :profile
    else # いずれでもなければ全てのアクションを不許可
      cannot :manage, :profile
    end
  end
end

参考

基本的な使い方は以下などを参考にすると良いと思います。
Rails|CanCanCanの使い方解説

2
0
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
2
0