2012-05-24 36 views
1
新的形式失敗

我有用戶慘慘 - 當用戶限制到特定的網站

class User < ActiveRecord::Base 
    devise :database_authenticatable, 
     :recoverable, :rememberable, :trackable, :validatable 


    attr_accessible :email, :password, :password_confirmation, 
        :remember_me, :site_id, :role_name 

    belongs_to :site 

end 

網站

class Site < ActiveRecord::Base 
    has_many :users 
    has_one :front_page_campaign 
end 

和front_page_campaigns

class FrontPageCampaign < ActiveRecord::Base 
    belongs_to :site 
end 

我使用康康舞限制訪問,因此用戶只能管理front_page_campaigns爲自己的網站:

class Ability 
    include CanCan::Ability 

    def initialize(user) 
    user ||= User.new # guest user (not logged in) 

    case user.role_name 

    when "super_admin" 
     # can do everything 
     can :manage, :all 

    when "editor" 
     # can edit content for their site 
     can [:create, :read, :update], FrontPageCampaign, site_id: user.site_id 

    end 
    end 
end 

這對於角色名稱super_admineditor上的用戶在front_page_campaigns上的顯示和編輯完美適用。但是,當一個editor嘗試創建一個新的front_page_campaign,我得到一個康康舞禁止通知

You are not authorized to access this page. 

標準形式提供的所有站點的下拉框,我想我需要限制這僅僅是用戶自己的網站。我會如何去做這件事?

回答

1

你的授權問題通過添加解決:

can :new, FrontPageCampaign 

到慘慘能力的init的編輯欄。 設置SITE_ID對新創建的對象,你可以設置的before_filter:

# FrontPageCampaignsController 
before_filter :set_site_id, :only => [:new, :create] 

protected 

def set_site_id 
    @resource.site_id = current_user.site_id if current_user && current_user.role_name == 'editor' 
end 

你必須確保在創建資源此大火後卻可以授權之前。

在表單(如果您使用超級管理員和編輯一樣)使網站下拉選擇只讀或隱若current_user.role_name == 'editor'

需要注意的是,如果有人與形式篡改,併發送一個外國人SITE_ID作爲編輯,它將由前過濾器,這是不是很好糾正。如果你把如果並有:only => :new那麼他們將被康康舞得到授權錯誤。如果你是超級學生,你應該得到一個有效的迴應與驗證錯誤。您可以通過1實現這一目標)將唯一的before_filter爲新2)能力說的init

when "editor" 
    # can edit content for their site 
    can [:read, :update], FrontPageCampaign, site_id: user.site_id 
    can [:create, :new], FrontPageCampaign 
end 

和3)添加網站所有者檢查,模型驗證。這是我首選的方式,爲非法訪問現有資源保留授權錯誤。

希望這回答你的問題

+0

感謝您的深入解答 - 非常有用。我認爲':create'被別名爲包含':new',但是它恰恰相反! – Edward