【问题标题】:Rails more than one index pageRails 不止一个索引页
【发布时间】:2015-12-23 23:21:19
【问题描述】:

我有一个模型调用问题,我需要 2 个索引页。一个用于所有问题,一个用于所有官方问题(仅适用于我的“官方”专栏的问题)。我将如何去做这件事。到目前为止,我只有返回所有问题的索引

    def index 
        @questions = Question.paginate(page: params[:page], per_page: 3)
    end

【问题讨论】:

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


    【解决方案1】:

    我不确定我是否理解,这就是为什么我会提出两种方法:

    1) 您可以有 2 个不同的网址和视图 - 一个用于所有问题,一个用于官员

    def index 
        @questions = Question.paginate(page: params[:page], per_page: 3)
    end
    
    def official 
        @questions = Question.where(official: true).paginate(page: params[:page], per_page: 3)
    end
    

    2) 如果您想在一页中呈现两个列表:

    def index 
        @all_questions = Question.paginate(page: params[:page], per_page: 3)
        @official_questions = Question.where(official: true).paginate(page: params[:page], per_page: 3)
    end
    

    【讨论】:

    • 第一个我需要修改我的 routes.rb 文件,目前是“resources :questions”
    • 是的,您应该添加:get 'questions/official', to: 'questions#official'
    【解决方案2】:

    我觉得你有点糊涂了。

    您可以使用 one index 方法和视图来做到这一点。您可能有不同的选择,但最终,您将有一种方法可以根据您发送的请求进行填充:

    #config/routes.rb
    resources :questions do
       get :official, to: :index, on: :collection, official: "true" #-> url.com/questions/official
    end
    
    #app/controllers/questions_controller.rb
    class QuestionsController < ApplicationController
       def index
          if params[:official]
             @questions = Question.where(official: true)
          else
             @questions = Question.all
          end
          @questions = @questions.paginate(page: params[:page], per_page: 3)
       end
    end
    

    然后你会使用:

    #app/views/questions/index.html.erb
    <%= render @questions %>
    
    #app/views/questions/_question.html.erb
    <%= question.title %>
    

    您不需要partial(我喜欢它,因为它模块化了您正在做的事情)-需要注意的重要一点是您基本上每次都在填充@questions -- index 视图只是用作查看其中包含的数据的一种方式。

    因此,您不需要两个索引方法——您可以只设置一个自定义链接并在控制器中使用一些条件逻辑来确定要使用的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      • 2013-09-11
      相关资源
      最近更新 更多