Reputation: 112
I want 3 user levels as Admin ,Manager,Customer in my rails application. So i've created a devise model as Users and added a migration to add the user role to it.So when a user is signed up it stores the users role(whether he is an admin,a manager or a customer). And in my application there are models and controllers for product,delivery,services. And I want to set access levels to each models.
So Admin have access to all models, controllers
Manager have access to Product, Delivery
Customer have access to Services
And i've written the Ability model as follows.
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.roles == "admin"
can :manage , :all
elsif user.roles == "manager"
can :read, Products, Delivery
elsif user.roles == "customer"
can :read, Services
end
end
end
My show view for the product is as follows.
<% if can? :manage ,@products%>
<h1>Products</h1>
<% @products.each do |product| %>
<p> <%= product.name%>
<p> <%= product.price %><br>
<p> <%= product.qty %><br>
<%end%>
<%end%>
But even i sign in as an admin the data is not displayed. I'm referring the following cancan documentation. https://github.com/CanCanCommunity/cancancan/wiki/Role-Based-Authorization The code seems to be okay with "One role per user" But the data is not displayed.Please help me to solve this issue.
Upvotes: 0
Views: 60
Reputation: 112
All the codes were correct but the issue was with the strong parameters.Therefor when signing up "role" has not saved in the database.Therefor when the ability is checked the users are not passed to view the content as non of they are admins,managers or customers
Upvotes: 0
Reputation: 51
I'm no real expert at CanCan, but You may try:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
cannot :manage, :all # we can do this since the abilities are OR'ed
if user.roles.include?('admin')
can :manage , :all
elsif user.roles.include?('manager')
can :read, Products, Delivery
elsif user.roles.include?('customer')
can :read, Services
end
end
end
Besides, if it's a project start, think about CanCanCan https://github.com/CanCanCommunity/cancancan
It's updated version of CanCan, still maintained by the Community.
Upvotes: 1