ruby-on-rails - 使用 CanCanCan - 我显然在做一些明显错误的事情
问题描述
晚上好,
CanCanCan 很棒;但是,我认为我遗漏了一些非常明显的东西,因为我的模型逻辑非常简单。
- 生成事物的登录用户应该能够读取、更新和删除
- 如果不是事物作者的登录用户应该能够阅读和评论事物。
- 未登录的人应该能够阅读和/或搜索。
第 1 步和第 3 步有效。但是,第 2 步不起作用 - 如果另一个用户已登录,则尝试查看某个东西;他们看到“CanCan::AccessDenied”,除非这是他们的事。
能力.rb
if user.present?
can :manage, List, user_id: user.id
else
can [:read, :search], List
end
是否user.present?
链接/锁定到上述代码段中的 current_user?我试过省略 .present? 但是,这仍然呈现 CanCan::AccessDenied。
对于这个意外错误,我认为类似下面的方法会起作用,唉。
if user.present?
can :manage, List, user_id: user.id
elsif @list.find(params[:id]).user != user
can [:read], List
else
can [:read, :search], List
end
对于后代,请在 Roman Alekseiev 提供的基础上找到我的解决方案。
应用控制器
class ApplicationController < ActionController::Base
load_and_authorize_resource :parent
load_and_authorize_resource :child, through: :parent
能力.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= ::User.new
if user.new_record?
can [:read, :search], Parent
can [:read], Child
else
can [:read, :search], ::Parent
can [:read, :create, :delete], Child
can :manage, Parent, user_id: user.id
end
end
如何使用视图中的能力,例如显示。
<% if can? :create, @parent => Child %>
present the child markup/content
<% end %>
解决方案
在我看来,我的观点是:
def initialize(user)
user ||= ::User.new
if user.new_record?
can [:read, :search] ::List
else
can [:read, :comment], ::List
can :manage, ::List, user_id: user.id
end
用这篇文章试过,来源
推荐阅读
- c# - 如何在 C# 上从 Oracle 调用函数?
- javascript - 如何创建 JS Canvas 自上而下的雨效果或反向扭曲速度
- mysql - MYSQL 在哪里存储“UPDATE CURRENT_TIMESTAMP”的逻辑
- c# - 如何让 EF Core 设计工具读取自定义配置?
- apache-superset - 如何更改 Superset 的表数据源?
- python - 如何访问熊猫数据框中的单个值
- mysql - 如何在发布帖子后立即通过 wp cron 启动 sql 查询?
- java - 如何按枚举字段对对象列表进行排序?
- sql - 为什么 Oracle 不能识别这种日期格式?
- java - 按数组元素搜索mongo文档