首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Cancan :创造能力

Cancan :创造能力
EN

Stack Overflow用户
提问于 2013-04-04 19:47:45
回答 1查看 868关注 0票数 1

我有以下代码:

代码语言:javascript
复制
#/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

我想检查只为用户创建自己的手机的能力

代码语言:javascript
复制
#/app/views/users/users/show.html.slim
- if can? :create, Users::Phone.new
  a[href="#{new_user_phone_path(@user)}"] Add phone

这不起作用,因为我应该将user_id传递给phone模型(如Users::Phone.new user_id: user.id),但由于Phone的批量赋值,我不能这样做。

那么,我如何才能检查用户的:create手机功能?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-04 21:35:41

我在我的应用程序中做了类似的事情,让Ability知道底层的参数结构。根据您的需求,您有几个选项。所以在你的控制器中,你大概会有:

代码语言:javascript
复制
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

然后在你的ability.rb中:

代码语言:javascript
复制
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
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15810236

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档