Created
November 26, 2015 07:04
-
-
Save ksugiarto/33f02d67dea53f78142c to your computer and use it in GitHub Desktop.
Rails CanCan's Usage Example
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 Ability | |
include CanCan::Ability | |
def initialize(user) | |
user ||= User.new # guest user | |
can [:read, :update], User do |user_profile| | |
user_profile.id == user.id | |
end | |
if user.role.to_i==1 # superAdmin | |
can :manage, :all | |
elsif user.role.to_i==2 # vendor | |
can :create, [Vendor, RoomType, Room, Facility] | |
can [:read, :update, :destroy], Vendor do |vendor| | |
vendor.try(:user) == user | |
end | |
can [:read, :update, :destroy], RoomType do |room_type| | |
room_type.try(:user) == user | |
end | |
can [:read, :update, :destroy], Room do |room| | |
room.try(:user) == user | |
end | |
can [:read, :update, :destroy], Facility do |facility| | |
facility.try(:user) == user | |
end | |
elsif user.role.to_i==3 # user | |
can :read, Room | |
# can :read, Facility | |
else # guestUser | |
can :read, Room | |
# can :read, Facility | |
end | |
end | |
end |
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 RoomsController < ApplicationController | |
before_action :set_room, only: [:show, :edit, :update, :destroy] | |
before_action :set_vendor | |
# Setting this for every action can be tedious, therefore the load_and_authorize_resource method is provided to automatically authorize all actions in a RESTful style resource controller. It will use a before filter to load the resource into an instance variable and authorize it for every action. | |
load_and_authorize_resource | |
def index | |
end | |
end |
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
<% if can? :create, Vendor %> | |
<div class="grid-row"> | |
<div class="grid-col grid-col-9"> | |
<div class="widget-title">My Vendor</div> | |
</div> | |
<div class="grid-col grid-col-3 text-right"> | |
<%= link_to new_vendor_path, :class => "btn btn-default btn-sm" do %> | |
<i class="fa fa-plus-circle"></i> Add New Vendor | |
<% end %> | |
</div> | |
<% if can? :update, Vendor %> | |
<%= render 'vendors/index_table' %> | |
<% end %> | |
</div> | |
<% end %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment