【问题标题】:Cancan :create ability康康:创造能力
【发布时间】:2013-04-04 11:47:44
【问题描述】:

我有以下代码:

#/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 用户的电话功能?

【问题讨论】:

    标签: ruby-on-rails cancan


    【解决方案1】:

    我通过让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
    

    【讨论】:

    • 戴夫,感谢您的解决方案,它按预期工作。为了正确检查:create 在我使用if can? :create, Users::Phone.new({user: @user}, without_protection: true) 的视图中的能力,其中@user 是我们要为其创建电话的所有者。
    • 谢谢!由于我通常在每个控制器的顶部加载_and_authorize_resource,将其修改为: load_and_authorize_resource except: :create 然后我手动调用授权!并如上所示传递我的对象。
    猜你喜欢
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    相关资源
    最近更新 更多