0

我有一個頁面模型,它有一個:名稱屬性。我有一個具有名稱「主頁」的頁面模型的具體路由,因爲我想在root_url找到這個特定的頁面記錄。這工作..但因爲我硬編碼的路線......我只想與作用「超級管理員」用戶能夠改變:name屬性,在頁模式,其中name ==「home」。例如,用戶與「管理員」的角色應該能夠改變:name屬性「家」頁。CanCan資源條件和friendly_id slugi的特殊路由

  1. Can Can can get that fine grained with CanCan?
  2. 我應該把這個邏輯放在PageControllers更新操作中嗎?
  3. 我應該設置「頁面#顯示」路線不同(不是硬代碼)嗎?

不知道如何做到這些。 在此先感謝您的任何建議!

ability.rb

elsif user.role == "admin" 
    can :manage, :all 
    cannot :update, Page, ["name == ?", "home"] do |page| 
    page.name == "home" 
    end 
end 

的routes.rb(我使用friendly_id以從蛞蝓:name屬性

match '/:slug', :to => "pages#show", :as => :slug, :via => :get 
root :to => 'pages', :controllers => "pages", :action => "show", :slug => "home" 

pages_controller.rb(標配)

def update 
    @page = Page.find(params[:id]) 

    respond_to do |format| 
    if @page.update_attributes(params[:page]) 
     format.html { redirect_to @page, notice: 'Page was successfully updated.' } 
     format.json { head :no_content } 
    else 
     format.html { render action: "edit" } 
     format.json { render json: @page.errors, status: :unprocessable_entity } 
    end 
    end 
end 

回答

1

我必須承認,我讀過你的問題三次,我想我有答案,你...

1 - 是的,我相信如此。但是,我不確信你的ability.rb代碼是正確的。我瞄準的東西接近這個:

cannot :update, Page do |page| 
    page.name == "home" 
end 

2 - 如果你在你的控制器做load_and_authorize_resource,這應該是你所需要的,因爲這將加載@page爲您服務。

class PagesController < ApplicationController 

    load_and_authorize_resource 

    def update 

    respond_to do |format| 
     if @page.update_attributes(params[:page]) 
     format.html { redirect_to @page, notice: 'Page was successfully updated.' } 
     format.json { head :no_content } 
     else 
     format.html { render action: "edit" } 
     format.json { render json: @page.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

end 

3 - 對我來說,你的路線看起來不錯。這可能是我接近它的方式。

+0

感謝您的意見。我也必須升級到CanCan 2.0。 –