2013-02-18 57 views
1

我有一組具有公共屬性的頁面。我想要路由文件處理動態路由,但只適用於公共頁面。動態路徑在軌條件下

我目前有以下,但沒有限制,所有頁面都可見。我想的是去頁面只有當頁面是公開的其他籌集404

Page.public.each do |page| 
    get "/:slug", controller: 'pages', action: 'show' if page.public? 
end 

回答

0

工作代碼(失蹤 '未找到')

class PagesController 

    before_filter :is_public, only => [:show] 

    protected 

    # Check if the page is public, otherwise raise a routing error. 
    def is_public 
    raise ActionController::RoutingError.new('Not Found') unless Page.find(params[:slug]).public? 
    end 
end 
2

我會把這種行爲的控制,而不是在routes.rb中,因爲一個頁面可以從私有到公有過程中改變運行時間和生產中的路線在開始時僅初始化一次。

class PagesController 

    before_filter :is_public, only => [:show] 

    protected 

    # Check if the page is public, otherwise raise a routing error. 
    def is_public 
     raise ActionController::RoutingError.new unless Page.find(params[:slug]).public? 
    end 
end 
+0

好一點。當前路線聲明中不需要更改? – olimart 2013-02-18 04:29:27

+0

當前聲明會爲每個頁面對象創建一個路徑'/:slug',所以我會用'get'/:slug',controller:'pages',action:'show''替換它。或者只是'get'/:slug'=>'pages#show''。我假設slug參數是某種參數化的唯一名稱,它會在給予Page.find – roo 2013-02-18 04:39:44

+0

時識別頁面。它在is_public方法中引發控制器錯誤參數的錯誤數量(0表示1) – olimart 2013-02-18 04:55:45