gpt4 book ai didi

ruby-on-rails - Rails cancan :manage all Offers as moderator which belong to the same Department

转载 作者:数据小太阳 更新时间:2023-10-29 08:09:25 26 4
gpt4 key购买 nike

我正在尝试解决以下问题:

class User < ActiveRecord::Base
belongs_to :department
has_many :offers
end

class Offer < ActiveRecord::Base
belongs_to :user
end

class Department < ActiveRecord::Base
has_many :users
end

用户类有一个角色属性。我希望 :moderator 角色能够管理与 :moderator 具有相同 department.id 的所有用户的所有优惠。到目前为止,我已经想出了以下内容:

class Ability
include CanCan::Ability

def initialize(user)
user ||= User.new # guest user (not logged in)
if user.is? :admin
can :manage, :all
elsif user.is? :moderator
# Moderators can manage Users which belong to the same Department
can :manage, User, :department_id => user.department_id
# Moderators can manage all Offers which share the same department.id as the manager
can :manage, Offer, :department => { :id => user.department_id}
elsif user.is? :registered
# User can manage their own Offers
can :manage, Offer, :user_id => user.id
else
can :read, Offer
end
end
end

但是线

can :manage, Offer, :department => { :id => user.department_id}

显示所有优惠,而不仅仅是我需要的优惠。知道如何更改线路吗?也许是 Offer 模型中的范围?

最佳答案

Ju Liu 的回答有效,还添加了

has_one :department, :through => :user

到 Offer 模型并使用我对

的原始定义
can :manage, Offer, :department => { :id => user.department_id}

似乎可以解决问题。

关于ruby-on-rails - Rails cancan :manage all Offers as moderator which belong to the same Department,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17315374/

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