Search code examples
ruby-on-railsruby-on-rails-4cancancancancan

Why does the output is not passing through the ability check in Role Based Authorization (One Role Per User)


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.


Solution

  • 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