【问题标题】:Incorrectly routing /index to /show in Rails在 Rails 中错误地将 /index 路由到 /show
【发布时间】:2016-07-21 20:52:58
【问题描述】:

这肯定有一个明显的答案,但我不知所措。

我有一个跟踪网站的 Rails 应用程序。无论出于何种原因, localhost:3000/sites 都会指向我的索引页面。但是, localhost:3000/sites/index 会导致我的显示页面。

这是为什么?

以下是路由文件:

Rails.application.routes.draw do

  resources :sites

以下是站点控制器:

class SitesController < ApplicationController

  def index
  end

  def show
  end

end

在视图/站点中,有 index.html.erb 和 show.html.erb 文件。前者显示在 /sites,后者显示在 /sites/index(和 /sites/show 正如人们所期望的那样)。

感谢您的帮助!

更新:

当我 rake 路线时,我得到:

Prefix Verb   URI Pattern               Controller#Action
sites GET    /sites(.:format)          sites#index
      POST   /sites(.:format)          sites#create
new_site GET    /sites/new(.:format)      sites#new
edit_site GET    /sites/:id/edit(.:format) sites#edit
 site GET    /sites/:id(.:format)      sites#show
      PATCH  /sites/:id(.:format)      sites#update
      PUT    /sites/:id(.:format)      sites#update
      DELETE /sites/:id(.:format)      sites#destroy

这些路由是人们所期望的,但我想我只是对站点/索引假定索引是一个 :id 并因此路由要显示的请求感到惊讶。

我想我以前从未明确遇到过这种行为。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    默认情况下,控制器中有 7 个基本操作,其中只有 2 个通过 url 中的名称匹配 - (newedit)。这两个是 HTML 结构,它们只是呈现表单的一种方式。

    其他 5 个(索引、显示、更新、创建、销毁)是更基本的路由,负责显示和修改资源。它们仅被 两个 url 模式引用(您上面提到的两个模式 - 例如“/sites”和“/sites/:id”)。它们的区别在于请求附带的方法:(Patch、Post、Get、Delete)。因此,“/sites”将用于createindex。 “/sites/:id”将用于showdestroyupdate

    控制器中的动作并没有被 url 准确引用 - url 模式和请求方法一起用于调用关联的控制器方法。

    在请求“/sites/index”中,由于字符串“index”在url中,唯一匹配的路由是在“/sites/”之后有一个变量的路由。 :id 只是一个变量,不一定是整数。由于请求是 GET,因此第一个(也是唯一的)路由匹配是 sites#show。 "index" 将是传递给 show 动作的 params[:id] 的值。

    【讨论】:

      【解决方案2】:

      这就是 Rails 中路由的工作方式。查看Rails routing 以更好地了解其工作原理。特别是 Rails resource routing 部分。

      通常,当您设置资源路由时,网址如下:

      example.com/sites #=> index page
      example.com/sites/:id #=> show page. A specific site, where :id would be the unique identifier
      
      # Here's an example URL with a specific site
      example.com/sites/stackoverflow
      

      【讨论】:

        【解决方案3】:

        您的索引页位于:localhost:3000/sites

        导航至localhost:3000/rails/info/routes 以查看您在开发模式下的完整应用路线。

        【讨论】:

          猜你喜欢
          • 2018-03-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-03-21
          • 2010-12-26
          相关资源
          最近更新 更多