【问题标题】:CanCanCan :read block not workingCanCanCan:读取块不起作用
【发布时间】:2017-06-28 11:52:55
【问题描述】:

我试图在 Rails 5 中对我的Property 类进行非常简单的授权。我已将can :read 条件添加到ability.rb 并在我的控制器中使用load_and_authorize_resource,但我什至不能让它撬开,更不用说授权:show 操作了。我错过了什么明显的东西吗?

# ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)

    can :read, Property do |property|
      binding.pry
      PropertyUser.find_by(property_id: property.id, user_id: user.id)
    end
  end
end




# properties_controller.rb

class PropertiesController < ApplicationController
  before_action :set_property, only: [:show, :edit, :update]
  load_and_authorize_resource
  skip_authorize_resource :only => [:new, :create]

  def show
    respond_to do |format|
      format.html
      format.js
    end
  end

  private

  def set_property
    @property = Property.find(params[:id])
  end
end

谢谢。

【问题讨论】:

  • AFAIK,它正在尝试授权控制器操作名称,因此您不会尝试授权:read,但是:show,也许就是这样。
  • 谢谢回复,其实我已经试过了,还是没解决问题
  • 还有几件事,我认为你可以摆脱set_property,无论哪种方式,Cancancan 都应该为你做到这一点。
  • 如果因为自定义名称需要,可以使用github.com/CanCanCommunity/cancancan/wiki/…
  • 啊,好的,谢谢,我不知道。尽管如此,授权​​显示页面仍然没有运气。

标签: ruby-on-rails ruby-on-rails-5 cancancan


【解决方案1】:

您可能需要在您的 user.rb 中包含此代码

delegate :can?, :cannot?, to: :ability

def ability
  Ability.new(self)
end

【讨论】:

  • 嗯,我以前有其他授权工作,所以我认为这不是问题。反正我试了一下,还是不行。
【解决方案2】:

您可以使用authorize_resource 而不是load_and_authorize_resource,然后检查。我认为我们在这里不需要delegate,因为CanCanCan 会自动执行此操作。它会自动将这些方法添加到User 模型中。

【讨论】:

  • 很高兴知道,但不幸的是它并没有解决问题
  • 你确定你的数据库中有 Property 对象吗?
  • 尝试调试如图here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多