Created
November 29, 2019 19:45
-
-
Save the-teacher/05a7f85237c756c4560017d31491597e to your computer and use it in GitHub Desktop.
roles-post-1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PostsController < ApplicationController | |
def index | |
# ... | |
end | |
def show | |
# ... | |
end | |
def create | |
# ... | |
end | |
def update | |
@post = @current_user.posts.find(params[:id]) | |
@post.update!(post_params) | |
redirect_to @post | |
end | |
private | |
def post_params | |
params.require(:post).permit(:title, :content) | |
end | |
end |
module Post
class AuthorAbilities
include Kan::Abilities
role(:author) do |user, post|
user.id == post.author_id
end
register(:read, :edit) { |_, _| true }
register(:delete) { |_, _| false }
end
class AdminAbilities
include Kan::Abilities
role(:admin) do |user, _|
user.admin?
end
register(:read, :edit, :delete) { |_, _| true }
end
end
class UserPolicy
attr_reader :current_user, :model
def initialize(current_user, model)
@current_user = current_user
@user = model
end
def index?
@current_user.admin?
end
def show?
@current_user.admin? or @current_user == @user
end
def update?
@current_user.admin?
end
def destroy?
return false if @current_user == @user
@current_user.admin?
end
end
require 'cancancan'
class Ability
include CanCan::Ability
def initialize(user)
send("#{user.role}_abilities", user)
end
def admin_abilities(user)
can :manage, :all
end
def member_abilities(user)
can :read, :all
can :manage, Article, { author_id: user.id }
can [:read, :update], User, { id: user.id }
end
def visitor_abilities(user)
can :read, :all
end
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://dbdiagram.io/home