ole*_*ole 1 ruby-on-rails cancan
我有以下代码:
#/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
Run Code Online (Sandbox Code Playgroud)
我想检查为用户创建自己的手机的能力
#/app/views/users/users/show.html.slim
- if can? :create, Users::Phone.new
a[href="#{new_user_phone_path(@user)}"] Add phone
Run Code Online (Sandbox Code Playgroud)
多数民众赞成不起作用,因为我应该将user_id传递给手机型号(如Users::Phone.new user_id: user.id),但我不能这样做,因为手机的质量分配.
那我怎么能检查:create手机的用户能力呢?
我通过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
Run Code Online (Sandbox Code Playgroud)
然后在你的能力.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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
660 次 |
| 最近记录: |