Rails MVC 和 CRUD(4)

2021-11-24 09:48:37 浏览数 (2)

下面是访问过程中产生的日志

代码语言:javascript复制
Started GET "/welcome/index" for 192.168.100.1 at 2016-04-22 20:16:03  0800
Cannot render console from 192.168.100.1! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by WelcomeController#index as HTML
  Rendered welcome/index.html.erb within layouts/application (0.2ms)
Completed 200 OK in 44ms (Views: 42.9ms | ActiveRecord: 0.0ms)

资源的CRUD

资源的创建、读取、更新和删除操作,简称为 CRUD。

我们来尝试创建资源

添加资源到 route

代码语言:javascript复制
[root@h202 blog]# vim config/routes.rb 
[root@h202 blog]# grep -v ' #' config/routes.rb | grep -v "^$"
Rails.application.routes.draw do
  resources :articles
  root 'welcome#index'
end
[root@h202 blog]# rake routes
      Prefix Verb   URI Pattern                  Controller#Action
    articles GET    /articles(.:format)          articles#index
             POST   /articles(.:format)          articles#create
 new_article GET    /articles/new(.:format)      articles#new
edit_article GET    /articles/:id/edit(.:format) articles#edit
     article GET    /articles/:id(.:format)      articles#show
             PATCH  /articles/:id(.:format)      articles#update
             PUT    /articles/:id(.:format)      articles#update
             DELETE /articles/:id(.:format)      articles#destroy
        root GET    /                            welcome#index
[root@h202 blog]#

结果展示了当前的一系列 Restfull API 与 Controller#Action 的对应关系

我们尝试访问其中的一个链接,/articles/new 得到如下反馈

报错的原因为没有 ArticlesController


创建控制器

代码语言:javascript复制
[root@h202 blog]# bin/rails g controller articles
Running via Spring preloader in process 12913
      create  app/controllers/articles_controller.rb
      invoke  erb
      create    app/views/articles
      invoke  test_unit
      create    test/controllers/articles_controller_test.rb
      invoke  helper
      create    app/helpers/articles_helper.rb
      invoke    test_unit
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/articles.coffee
      invoke    scss
      create      app/assets/stylesheets/articles.scss
[root@h202 blog]# ll app/controllers/articles_controller.rb 
-rw-r--r-- 1 root root 53 Apr 22 20:49 app/controllers/articles_controller.rb
[root@h202 blog]# cat app/controllers/articles_controller.rb 
class ArticlesController < ApplicationController
end
[root@h202 blog]# 

0 人点赞