Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access CanCan's `can?` method from a model

You can get the current_user's permissions from a view or controller using can? in this fashion:

  <% if can? :update, @article %>     <%= link_to "Edit", edit_article_path(@article) %>   <% end %> 

How can I access this functionality from a model using this syntax:

user.can?(:update, @article) 
like image 232
Tom Lehman Avatar asked Jul 20 '10 19:07

Tom Lehman


1 Answers

There's a wiki entry at github for this: https://github.com/ryanb/cancan/wiki/ability-for-other-users

You need to change your User model like this:

class User < ActiveRecord::Base   def ability     @ability ||= Ability.new(self)   end   delegate :can?, :cannot?, :to => :ability end 

Then you can check abilities like this:

user.can?(:update,@article) 
like image 180
jigfox Avatar answered Sep 20 '22 06:09

jigfox