我有以下代码:
#/app/models/users/user.rb
class Users::User < ActiveRecord::Base
has_many :phones, class_name: "Users::Phone"
end
#/app/models/users/phone.rb
class Users::Phone < ActiveRecord::Base
belongs_to :user, class_name: "Users::User"
attr_accessible :phone
end
#/app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
can :read, :all
unless user.nil? #logged_in
if user.is? :admin
can :manage, :all
else
can :create, Users::Phone, user_id: user.id
end
end
end
end
我想检查为用户创建自己的手机的能力
#/app/views/users/users/show.html.slim
- if can? :create, Users::Phone.new
a[href="#{new_user_phone_path(@user)}"] Add phone
多数民众赞成不起作用,因为我应该将user_id传递给手机型号(如Users::Phone.new user_id: user.id
),但是自从手机的质量分配后我无法做到这一点。
那么我如何检查用户的:create
电话能力?
答案 0 :(得分:5)
通过让Ability
了解底层参数结构,我在我的应用程序中做了类似的事情。根据您的要求,您有几个选择。所以在你的控制器里,你有大约:
def create
@phone = Users::Phone.new(params[:users_phone])
# Optional - this just forces the current user to only make phones
# for themselves. If you want to let users make phones for
# *certain* others, omit this.
@phone.user = current_user
authorize! :create, @phone
...
end
然后在你的能力.rb:
unless user.nil? #logged_in
if user.is? :admin
can :manage, :all
else
can :create, Users::Phone do |phone|
# This again forces the user to only make phones for themselves.
# If you had group-membership logic, it would go here.
if phone.user == user
true
else
false
end
end
end
end