Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

ruby on rails - 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...