【问题标题】:How come the the index action renders the show view?index 操作如何呈现显示视图?
【发布时间】:2014-03-24 23:45:47
【问题描述】:

我注意到控制器中的索引操作(方法)通常会呈现显示视图。

例如:

/posts/index 

在我的localhost 上时呈现显示视图。虽然简单

/posts

呈现索引。为什么是这样?我还没有找到任何解释这个的地方?

我对 Rails 还很陌生,谢谢!

【问题讨论】:

    标签: ruby-on-rails views


    【解决方案1】:

    /posts 映射到index 动作的路由。

    /posts/index 映射到show 动作的路线。你会收到一条错误消息Cannot find a post with id=index.

    为资源posts 生成的路由如下:

         posts GET    /posts(.:format)                                              posts#index
               POST   /posts(.:format)                                              posts#create
    new_post   GET    /posts/new(.:format)                                          posts#new
    edit_post GET    /posts/:id/edit(.:format)                                     posts#edit
    post      GET    /posts/:id(.:format)                                          posts#show
              PATCH  /posts/:id(.:format)                                          posts#update
              PUT    /posts/:id(.:format)                                          posts#update
              DELETE /posts/:id(.:format)                                          posts#destroy
    

    Rails 会将路径 /posts/index 匹配到显示操作之一,即 /posts/:id

    【讨论】:

      【解决方案2】:

      添加路线时

      resources :your_controller
      

      rails 默认创建主要的 7 个方法 [index,show,new,create,edit,update,delete)。

      Index 和 show 都是获取请求,但是 index 在控制器名称之后不需要 id

      就像在你的示例 /posts 中一样,但是 show 期望在你的控制器名称之后有一个 id,因为它的路由是这样的

      /posts/:id 
      

      所以 "/posts/" rails 之后的任何参数都将其解释为 id

      【讨论】:

        猜你喜欢
        • 2019-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多