简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM