0

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.

Edgar
  • 543
  • 10
  • 20
  • Since you're using Devise, have a look [here](https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address#rails-4). – actaram Mar 26 '15 at 23:27

1 Answers1

1

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.

MarsAtomic
  • 10,436
  • 5
  • 35
  • 56