我有以下代码:
#/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
用户的手机功能呢?