【问题标题】:Showing index view for all categories in a survey显示调查中所有类别的索引视图
【发布时间】:2015-05-02 06:35:48
【问题描述】:

在 Rails 中,我有两个模型,调查和类别。调查有_许多类别和类别属于_调查。我有一个显示我所有调查的索引页面,我想要一个按钮,将用户引导到一个视图,该视图显示每个单独调查的所有类别的索引。所以基本上我希望他们单击​​按钮并转到 /surveys/:id/categories 之类的内容。我该怎么做呢?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    首先定义路线:

    # config routes.rb
    resources :surveys, only: [:index] do
      resources :categories, only: [:index]
    end
    

    使用resources 为我们提供了不错的宁静路线:

    $ rake routes

               Prefix Verb URI Pattern                              Controller#Action
    survey_categories GET /surveys/:survey_id/categories(.:format) categories#index
              surveys GET /surveys(.:format) 
    

    检查前缀列 - 这意味着我们可以通过survey_categories_path(survey_id: @survey.to_param) 获得类别的路径。

    然后我们需要一个用于类别的控制器:

    class CategoriesController < ApplicationController
      def index
        # We use eager_load to get survey and categories in one DB query
        @survey = Survey.eager_load(:categories).find(params[:survey_id])
        @categories = @survey.categories
      end
    end
    

    【讨论】:

    • 谢谢,我只需在我的调查索引循环中将@survey.to_param 更改为survey.id,她就可以工作了!
    【解决方案2】:

    类似:

    routes.rb

    ...
    get 'surveys/:id/categories', :to => 'categories#index'
    ...
    

    categories_controller:

    ...
    def index
      @categories = Survey.find(params[:id]).categories
    end
    ...
    

    【讨论】:

    • 我宁愿遵循 Rails 在为嵌套资源 /parent/:parent_id/child 进行路由时使用的约定。当您添加 params[:id] 指的是孩子而不是父母的显示操作时,它就不那么令人困惑了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多