1

我有以下代码:

#/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用户的手机功能呢?

4

1 回答 1

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

然后在你的ability.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
于 2013-04-04T13:35:40.883 回答