【问题标题】:routes with the same resource multiple times多次使用相同资源的路由
【发布时间】:2015-02-12 07:31:11
【问题描述】:

我有一个模型示例,其中包含多个:用户,但也属于一个组。我想要一个仅包含示例的索引和另一个组示例的索引。 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 和 url.com/groups/1/examples 上。

我已经搜索并搜索并搜索了有关此问题的答案,但由于某种原因我找不到解决方案。

【问题讨论】:

    标签: ruby-on-rails model-view-controller rails-routing


    【解决方案1】:

    如果您从嵌套路由来到那里,您可以在examples_controller 中签入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
    

    【讨论】:

    • 由于某种原因,它们仍然出现在 /examples 和 /groups/1/examples 上
    • 好的,我将 @group = Group.find(params[:group_id]) 投入到索引操作中,它有点帮助,现在在 .com/groups/1/examples 中它只显示该小组创建了示例,但在 .com/examples 中仍显示所有示例。
    • @DylanLittle 我认为/examples 应该显示所有示例。期望的行为是什么?
    • 对不起。我的意思是 /examples 应该只显示不在一个组下的示例。或者换句话说 where(group_id: nil)
    • @DylanLittle 我相应地编辑了我的答案。您需要做的就是添加where(group_id: nil) 范围。
    猜你喜欢
    • 1970-01-01
    • 2021-04-21
    • 2018-02-18
    • 2013-11-04
    • 2014-04-08
    • 2019-05-23
    • 2021-05-26
    • 2022-01-17
    • 2021-12-19
    相关资源
    最近更新 更多