我有一个User
,Product
和一个Subscription
模型。基本上,订阅是针对特定产品的,一个产品可以有多个订阅,每个产品都属于一个用户(即作者)。用户可以是管理员或普通用户。
我的问题是:如果我想让我的普通用户只为他们创作的产品创建订阅,我将如何使用 cancan 来实现呢?
这就是我目前在我的能力.rb 中所拥有的。
class Ability
include CanCan::Ability
def initialize(user)
if user
if user.admin?
can :manage, :all
else # not an admin
can :read, User
can :manage, User, id: user.id
cannot :create, User
can :read, Product
can :manage, Product, user: user
can :read, Subscription
# this is sort of what I want, but now nobody can create subscriptions
can :create, Subscription, product: { user: user }
can :manage, Subscription, product: { user: user }
end
else # not a user, just a guest
can :create, User
can :read, User
can :read, Product
can :read, Subscription
end
end
end
我完全错了吗?我应该在控制器中执行此操作还是使用某种验证?