2013-04-04 54 views
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手機的能力?

回答

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 
+0

戴夫,感謝您的解決方案,它正常工作。爲了在視圖中正確檢查':create'能力,我使用了'if can? :create,Users :: Phone.new({user:@user},without_protection:true)'其中'@ user'是我們要爲其創建電話的所有者。 – ole 2013-04-04 19:09:11

+1

謝謝!由於我通常在每個控制器的頂部load_and_authorize_resource,將其修改爲: load_and_authorize_resource除外:: create 然後我手動調用授權!並按照上圖所示傳遞我的對象。 – Emeka 2016-10-11 23:08:55