2015-02-12 21 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

相关问题