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

Ruby on-RailsCancan

Ruby on-Rails Problem Overview


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)

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTom LehmanView Question on Stackoverflow
Solution 1 - Ruby on-RailsjigfoxView Answer on Stackoverflow