多次路由相同的资源

routes with the same resource multiple times

我有一个模型示例,其中 has_many :users 还有 belongs_to 一个组。我想要一个仅包含示例的索引和组示例的另一个索引。喜欢 - 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 和 url 上.com/groups/1/examples。

我搜索了又搜索了这个问题的答案,但出于某种原因我找不到解决方案。

如果您从嵌套路线到达那里,您可以在 before_filter 中签入 examples_controller 并相应地设置控制器的行为。例如:

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