2015-02-12 20 views
1

我有一個模型has_many:用戶,但也belongs_to組示例。我想有一個只是示例和另一個組示例索引的索引。 like-url.com/examples(只應顯示沒有group_id的示例)和url.com/group/1/examples。目前我的路線文件看起來像這樣:路線具有相同的資源多次

Rails.application.routes.draw do 

resources :groups do 
    resources :examples 
end 

resources :examples 

但我相信你知道這產生了一個問題,因爲索引操作與使所有的例子來顯示在兩個url.com/examples和網址的.com /組/ 1 /實施例。

我已搜索並搜索並在此搜索了一個答案,但由於某種原因,我無法找到解決方案。

回答

3

如果您是通過嵌套路由來到並且相應地設置控制器的行爲,則可以在中檢入before_filter。例如:

class ExamplesController < ApplicationController 
    before_filter :set_group, if: -> { params[:group_id].present? } 
    def index 
    @examples = if @group 
        @group.examples 
       else 
        Example.where(group_id: nil) 
       end 
    end 
    # ... 
    private 
    def set_group 
    @group = Group.find(params[:group_id]) 
    end 
end 
+0

出於某種原因,它們仍然顯示在兩者/示例和/基團/ 1 /實施例向上 – 2015-02-12 07:45:31

+0

沒關係我扔@group = Group.find(PARAMS [:GROUP_ID])到索引操作和它有一點幫助,現在在.com/groups/1/examples中它只顯示組創建的示例,但在.com /示例中它仍顯示所有這些示例。 – 2015-02-12 07:49:42

+0

@DylanLittle我以爲'/ examples'應該顯示所有的例子。期望的行爲是什麼? – 2015-02-12 07:50:41

相關問題