Access CanCan's `can?` method from a model
Asked Answered
S

1

51

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)
Sherikasherill answered 20/7, 2010 at 19:6 Comment(1)
Good question. Glad you also got a good answer on it!Deciduous
P
75

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)
Prophylaxis answered 20/7, 2010 at 19:19 Comment(1)
For CanCanCan: github.com/CanCanCommunity/cancancan/wiki/…Polybius

© 2022 - 2024 — McMap. All rights reserved.