1. gem "cancan"
2. install bundle.
3. rails g cancan:ability
this will generate an ability class in your models.
define your Abilities there like below.
but keep remember that you have already defined roles,
such as you have a User model,
having two roles defined i.e admin and support.
class
Ability
include
CanCan::Ability
def
initialize(user)
user||=
User.new
can
:read, :all
if
user.role == 'admin'
can
:manage, :all
else
can
:read, :all
end
end
end
4. the resource on which you want to restrict a user,
use the following filter in their controller.
use the following filter in their controller.
load_and_authorize_resource
5. if you want restrict something in the views not to show.
<% if can? :manage,
@flower %>
<td><%= link_to
'Edit', edit_flower_path(flower) %></td>
<% end %>
<% if can? :manage,
@flower %>
<td><%= link_to
'Destroy', flower_path(flower),
method: :delete, data: {
confirm: 'Are you sure?' } %></td>
<% end %>
No comments:
Post a Comment