プログラミングマガジン

プログラミングを中心にIT技術をできるだけわかりやすくまとめます。

  • ホーム
  • Ruby on Rails
  • 【Ruby on Rails】「cancancan」について
 
 
     
  • サーバー言語  
    • Python
    • Ruby
    • PHP
    • SQL
  •  
  • インフラ  
       
    • AWS
    •  
    • 基本
    • Git
  • Web
       
    • Web開発
    • JavaScript
    • Vue.js
    • React
  •  
  • 設計  
       
    • 実装設計
    • DB設計
  • 問い合わせ
  

【Ruby on Rails】「cancancan」について

01.10

  • miyabisan2
  • コメントを書く

この記事は2分で読めます

cancancanとは?

Railsで権限を管理するためのGemです。基本的には開発現場では認証用のGemであるdeviseと共に実装することが多いようです。deviseの使い方については下記の記事で解説しています。

【Ruby on Rails】「devise」、「devise_invitable」について

インストール

Gemfileに下記の記述をします。

1
gem 'cancancan'

bundleインストールします。

1
bundle install

前提

deviseを利用した際にusersモデルを作成すると思います。カラムは下記のようになっていると思います。(sqliteにて確認)

1
2
3
4
5
6
7
8
9
sqlite> PRAGMA table_info('users');
0|id|integer|1||1
1|email|varchar|1|''|0
2|encrypted_password|varchar|1|''|0
3|reset_password_token|varchar|0|NULL|0
4|reset_password_sent_at|datetime|0|NULL|0
5|remember_created_at|datetime|0|NULL|0
6|created_at|datetime|1||0
7|updated_at|datetime|1||0

下記のコマンドを実行してusersテーブルにroleというカラムを追加します。

1
rails g migration add_role_to_users

下記のように記述します。integer型で数字で権限を管理します。1が一般権限でデフォルトの値とします。

1
2
3
4
5
class AddRoleToUsers < ActiveRecord::Migration[5.2]
  def change
    add_column :users, :roll, :integer, null: false,default: 1
  end
end

マイグレーションします。

1
rails db:migrate

rollというカラムがusersに追加されました。

1
2
3
4
5
6
7
8
9
10
sqlite> PRAGMA table_info('users');
0|id|integer|1||1
1|email|varchar|1|''|0
2|encrypted_password|varchar|1|''|0
3|reset_password_token|varchar|0|NULL|0
4|reset_password_sent_at|datetime|0|NULL|0
5|remember_created_at|datetime|0|NULL|0
6|created_at|datetime|1||0
7|updated_at|datetime|1||0
8|roll|integer|1|1|0 ★new

cancancanの使い方

Abilityクラスを追加します。

1
rails g cancan:ability

下記のファイルが「app/models/ability.rb」に作成されます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Ability
  include CanCan::Ability
 
  def initialize(user)
    # Define abilities for the passed in user here. For example:
    #
    #   user ||= User.new # guest user (not logged in)
    #   if user.admin?
    #     can :manage, :all
    #   else
    #     can :read, :all
    #   end
    #
    # The first argument to `can` is the action you are giving the user
    # permission to do.
    # If you pass :manage it will apply to every action. Other common actions
    # here are :read, :create, :update and :destroy.
    #
    # The second argument is the resource the user can perform the action on.
    # If you pass :all it will apply to every resource. Otherwise pass a Ruby
    # class of the resource.
    #
    # The third argument is an optional hash of conditions to further filter the
    # objects.
    # For example, here the user can only update published articles.
    #
    #   can :update, Article, :published => true
    #
    # See the wiki for details:
    # https://github.com/CanCanCommunity/cancancan/wiki/Defining-Abilities
  end
end

下記のように書き直します。これはアプリが起動する際に読み込まれるcancancanの権限初期化設定になります。userにはdeviseでログインしたユーザー情報が入るのでdeviseで割り振った権限情報に基づいて任意の権限を設定することが可能です。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Ability
  include CanCan::Ability
 
  def initialize(user)
    user ||= User.new
 
    if user.roll == 2
      can :manage, :all
    elsif user.roll == 1
      can :read, :hello
    end
  end
end

can :権限, :権限を設定するモデル名

モデルに対して権限を設定します。

権限の種類

基本的には権限には5つの権限があります。(もちろん独自にコントローラに追加したアクションも追加することが可能です。)

権限の種類 説明
create 作成権限を持つ
read 読み取り権限を持つ
update 更新権限を持つ
destroy 削除権限を持つ
manage 全ての権限を持つ

モデルに紐づいていないページへアクセス制御をしたい場合

userというページを表示させたくない場合は下記のようになります。

1
cannot :index, :user

任意のビュー側に下記のような記述をすれば権限によるビューの制御が可能になります。

1
2
3
<% if can? :read, :hello %>
  <p>read権限があります</p>  
<% end %>

スポンサーリンク
  • 2020 01.10
  • miyabisan2
  • コメントを書く
  • Ruby on Rails
  • Tweets Twitter
  • このエントリーをはてなブックマークに追加
  • LINEで送る

関連記事

  1. 2021 02.06

    【Rails】「find_or_initialize_by」や「find_or_create_by」について

  2. 2020 12.19

    【Ruby on Rails】「アソシエーション(has_one)」、「belongs_to」のオプション

  3. 2020 12.26

    【Ruby on Rails】「ActionView::Helpers」や「FormBuilder」について

  4. 2019 11.30

    【Ruby on Rails】パーシャルを使ったビューの共通化、ロジックの共通化、HtmlBuilder

  5. 2019 12.01

    【Rspec】itのマッチャの種類(カスタムマッチャ、aggregate_failuresなども)

  6. 2020 03.15

    【Ruby on Rails】「フィクスチャ」について

  • コメント ( 0 )
  • トラックバック ( 0 )
  1. この記事へのコメントはありません。

  1. この記事へのトラックバックはありません。

返信をキャンセルする。

【Ruby on Rails】「devise」、「de…

【Docker】MySQLのコンテナに接続して基本操作…

RETURN TOP

著者プロフィール

エンジニア歴10年で過去に業務系、Webデザイン、インフラ系なども経験あります。現在はWeb系でフロントエンド開発中心です。

詳細なプロフィールはこちら

スポンサーリンク

カテゴリー

  • Android
  • AngularJS
  • API
  • AWS
  • C++
  • CSS
  • cursor
  • C言語
  • DDD
  • DevOps
  • Django
  • Docker
  • Figma
  • Git
  • GitLab
  • GraphQL
  • gRPC
  • Hasura
  • Java
  • JavaScript
  • Kubernetes
  • Laravel
  • linux
  • MySQL
  • Next.js
  • nginx
  • Node.js
  • NoSQL
  • Nuxt.js
  • Oracle
  • PHP
  • Python
  • React
  • Redux
  • Rspec
  • Ruby
  • Ruby on Rails
  • Sass
  • Spring Framework
  • SQL
  • TypeScript
  • Unity
  • Vue.js
  • Webサービス開発
  • Webデザイン
  • Web技術
  • インフラ
  • オブジェクト指向
  • システム開発
  • セキュリティ
  • その他
  • データベース
  • デザインパターン
  • テスト
  • ネットワーク
  • プログラミング全般
  • マイクロサービス
  • マイクロソフト系技術
  • マルチメディア
  • リファクタリング
  • 副業
  • 未分類
  • 業務知識
  • 生成AI
  • 設計
  • 関数型言語
RETURN TOP

Copyright ©  プログラミングマガジン | プライバシーポリシー