从模型访问CanCan的can方法 [英] Access CanCan's `can?` method from a model

查看:86
本文介绍了从模型访问CanCan的can方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以使用 can?从视图或控制器中获得 current_user 的权限: / p>

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)


推荐答案

在github上有一个Wiki条目: https://github.com/ryanb/cancan/wiki/ability-for-other-users

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)

这篇关于从模型访问CanCan的can方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆