【问题标题】:CanCan Double Nested Resource Permission ProblemCanCan 双重嵌套资源权限问题
【发布时间】:2023-03-18 17:30:01
【问题描述】:

我在定义两次嵌套资源的权限时遇到了一些问题。我有用户 > 公司 > 订单...

我的用户通过协议拥有许多公司。

每个公司都有很多订单,每个订单都属于一个公司。

我的abilities.rb 文件包含以下内容:

elsif user.role? :customer_admin
      can [:read, :update], User, :id => user.id
      can [:read, :update], Company, :id => user.id 
      can :read, Company, :users => { :id => user.id }
      can :read, Order, :user => { :id => user.id }
 end

在我的订单控制器中,我有这个:

 load_and_authorize_resource :company
  load_and_authorize_resource :order, :through => :company

问题是我似乎无法以 customer_admin 的身份查看订单

希望你能帮忙,再次感谢。

----编辑----

用户.rb

 has_and_belongs_to_many :roles
  has_many :agreements
  has_many :companies, :through => :agreements

公司.rb

  has_many :agreements
  has_many :users, :through => :agreements
  has_many :orders
  accepts_nested_attributes_for :orders

order.rb

  belongs_to :company
  has_many :comments
  has_many :tasks
  has_many :requirements
  has_many :services, :through => :requirements
  has_many :servicelevelagreements
  has_many :slas, :through => :servicelevelagreements

协议.rb

  belongs_to :user
  belongs_to :company

希望对你有帮助!!

【问题讨论】:

    标签: ruby-on-rails cancan


    【解决方案1】:

    您的订单中有user_id,它定义了管理员用户吗? 您似乎想在has_many :through 关联中使用它。如果是这种情况,那么我建议尝试通过这样定义来访问:

    can :read, Order, :company => { :user_id => user.id }
    

    由于cancan 支持嵌套关联。

    更新

    我的设置假设您的模型如下所示:

    #order.rb
    
    belongs_to :company
    
    #company.rb
    
    belongs_to :user
    has_many :orders
    

    您的公司应该包含一个名为 user_id 的字段,它是分配用户的 ID。

    有关更多信息,请参阅 wiki。 https://github.com/ryanb/cancan/wiki/Nested-Resources

    更新 2

    问题是你的companyhas_many :users, :through=>:agreements

    这涉及到以下定义:

    can :read, Order, :company => { :users => { :id => user.id } }
    

    【讨论】:

    • 感谢您的帮助。不,订单没有 user_id,因为它嵌套在公司控制器中。当我尝试这个时,我最终得到一个未经授权的错误:(我的 load_and_authorize_resource 位是否正确?Jx
    • @Jenny Blunt ,是的,你的 load_and_authorize 部分看起来不错。我认为你在角色声明部分有问题。如果您可以提供相关模型中定义的关系,我可以给您更具体的答案。更新了我的答案,请查看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多