gpt4 book ai didi

ruby-on-rails - 从模型访问 CanCan 的 `can?` 方法

转载 作者:行者123 更新时间:2023-12-03 06:18:42 25 4
gpt4 key购买 nike

您可以通过以下方式使用 can? 从 View 或 Controller 获取 current_user 的权限:

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

如何使用以下语法从模型访问此功能:

user.can?(:update, @article)

最佳答案

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

您需要像这样更改您的用户模型:

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

然后你可以像这样检查能力:

user.can?(:update,@article)

关于ruby-on-rails - 从模型访问 CanCan 的 `can?` 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3293400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com