[ruby on rails] 跟我学之(4)路由映射

前面《[ruby on rails] 跟我学之Hello World》提到,路由对应的文件是 config/routes.rb

实际上我们只是添加了一句代码: 

  resources :posts

但是这个代码默认的路由却有多个,可以通过 rake routes进行查看,如下:

root@tommy:/home/ywt/ror_tests/blog# rake routes
   Prefix Verb   URI Pattern               Controller#Action
    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

其中:

index   对应多个对象的列表

new     对应单个对象的新增页面

edit     对应单个对象的编辑页面

show   对应单个对象的现实页面

而, create/update/destroy是没有view(页面)文件的,处理实际的数据创建,更新,删除操作。

因此对于一个post对象,我们有7个action,其中四个有view文件。

修改 app/controllers/posts_controller.rb如下:

class PostsController < ApplicationController
  def index
  end

  def new
  end

  def create
  end

  def edit
  end

  def update
  end

  def show
  end

  def destroy
  end
end

新增文件 app/views/new.html.erb ,  app/views/edit.html.erb , app/views/show.html.erb, 分别对应 new 动作, edit动作, show动作。

此章节为后续做铺垫。

原文地址:https://www.cnblogs.com/Tommy-Yu/p/4141192.html