Edgar
Edgar

Reputation: 503

how to use cancancan with displaying certain aspect of a page to certain users

I am new to ruby on rails, i am using rails 4 and cancancan, i also using Devise gem. i have 4 different users, Admin, School, Franchise Owner, and regular users, i have an ability model which has this in it:

`class Ability include CanCan::Ability
def initialize(user)
user ||= User.new
if user.admin?
  can :manage, :all
elsif user.franOwner?
  can [:read], menus
elsif user.school?
  can :read, all
else 
  can :read, :all
  cannot [:create], Menu
 end
end`

and i have a link that i dont want regular users to see in a index.html.erb

  ` <% if user.admin? %>
    <%= link_to 'New Menu', new_menu_path %>
    <% end %>`

but says user is undefined, where do i define this and how? if i can get this working i might be able to replicate for other types of users for different things, and help would be greatly appreciated.

Upvotes: 0

Views: 147

Answers (1)

MarsAtomic
MarsAtomic

Reputation: 10696

According to the CanCanCan official documentation, you can use the can? method, along with the actual class when you don't have an instance of the class handy.

<% if can? :create, Menu %>
  <%= link_to 'New Menu', new_menu_path %>
<% end %>

can? takes a CanCan ability and an object or class as parameters. Make sure to capitalize the class so that CanCan knows you're dealing with a class and not an instance of the class. I do this very thing in my own application and it works fine.

Upvotes: 1

Related Questions