7. ROR:CRUD,REST and resourceful routes

CRUD

image.png
  • [Instructor] In this chapter, we will discuss several concepts which are important for the design of Rails applications. These concepts will affect the way that we work with URLs, how we write controller code, and how our controllers manage our models and database data. We're gonna start by talking about the concept of CRUD. Let's begin by reviewing the MVC web architecture diagram. First, we learned how to use controllers and views to create dynamic pages and return them back to the browser. Next, we shifted our focus and we learned to interact with the database by creating models and associations.

  • And we worked with those, not from a browser, but via the Rails console. Now, we need to put the two together and learn how to work with the models inside our controllers. Then we'll be able to manipulate our database data from the browser, in the same way, that we did from the console. The way that we're gonna work with the models and our controllers is using CRUD. CRUD is an acronym for creat, read, update and delete. And those are four actions that are the main ways in which we interact with our models and with the database. Because these four are so common, in Rails we have standard controller actions for implementing them.

  • You don't have to use these standard action names but they are the Rails convention and life will be easier if we stick with them. For each element of the CRUD, there are two actions associated with it. Let's begin by looking at the top two lines, create. Create has two actions, new and create. New will display a web form which will be filled out with the data that we want to send to the database. Then when we submit that web form, it's gonna submit to the create action. Create will process the form and either save the information to the data base or handle any errors that come up.

So new displays the form, create processes the form. It's a two-step process. Let's skip overread for a moment and go down to update because it works very similar to create. The difference is now with the update, there's existing data in the database. So it finds the existing data, we get a web form which is pre-populated with that data, we make any changes we want, we submit it to the update action, and the update action will process the form and submit those changes to the database. So edit displays the form, update processes the form.

And delete works the same way. Delete displays the information about the record we're about to delete. Destroy performs the destruction. The fourth part of CRUD, read, works a little bit differently. It does not have a display the form, process the form pairing. Instead it has two actions that are different. The first action is index, which returns a list of records. Show is an action which will display a single record, that is a detailed view of a single record in the database. So the first one is a list view, the second is a detail view.

Notice in the far right column of this table, there's a list of URLs which will be used to request these actions from the subject's controller. Most of these are self-explanatory. Index could include the word index after subjects but it's usually omitted and used as the default value. Notice that show, edit, update, delete and destroy all perform their work on an existing record. So they include the record ID in their URL. Index, new and create do not require an existing record so they do not. Together these eight actions are the core of working with CRUD in rails.

You will use them over and over again in every application that you build. Over the next two chapters, we're gonna learn how to implement them and use them to manage our subjects, pages, and sections in our CMS. I'll demonstrate how to add them for subjects and then later you'll have the opportunity to try adding them for pages and sections on your own. We're going to be dividing the CRUD for subjects, pages, and sections into three separate controllers. The subjects controller, the pages controller, and the sections controller. You typically have one controller per model.

It helps you to keep your code organized. And you're going to use plural names for your controllers. Notice it's subjects controller not subject controller because we are controlling all of our subjects with this controller not just one. This also allows for common sense URLs. For example, we will have subjects/new, pages/new, and sections/new, subjects/edit, pages/edit, and sections/edit and so on. These URLs clearly define the model which is being manipulated and the action which is being performed on it.

Let's generate a subjects controller and add placeholders for the basic CRUD actions. So inside my simple CMS, in my controllers, I still have my demo controller that we created earlier. We're gonna leave that there but we want to create a new controller now, for our subjects. You may recall the way we did that was from the root of our application, we typed rails, generate, and then controller and then what we wanted to name our controllers. Subjects, plural. Now before you hit return on this and generate the controller, I want to show you that there's also an option for generating controllers, where we can specify the views that we want it to create at the same time.

It's a helpful shortcut. So we'll put a space and then let's type out the actions that we have which will need views associated with them. We have our index and show, that's our list and our detail views. We're also gonna need forms for new, edit, and delete. Now that's only five of our eight actions, the other three are create, update and destroy but those don't actually have views associated with them. Those are just actions which do the form processing. So I don't need to have a view generated for them, just these five.

Let's hit return, it'll take a moment while it creates our subjects controller. Now if we come over and look, we have a subjects controller here. It went ahead and gave us some stubs for our actions. We have index, show, new, edit, and delete. And if we look in our views, you'll see that we have a subjects directory now and it includes placeholders for all of these different views. They just have some really simple text inside of them but we have a view there ready for us to fill out. So that's a handy trick. It really can save you a lot of time. Let's go ahead and add the other actions that we're gonna need, which don't have views.

In addition to new, we're gonna have create. In addition to edit, we're going to have update. In addition, to delete, we're going to have destroy. So that gives us the eight actions that we need. These are the ones for reading, index and show. Here's the ones for creating, new and create. And here's the ones for editing, edit update. And last of all, we have delete and destroy for deleting. We will learn to populate these actions in the next chapter. In order to use these actions, remember that we also need to add them to our routes file.

And that can be in our config directory. And inside routes. Now it gave us some placeholders for all of these actions here, subjects, new, edit, and delete and we would also need to add routes for the other actions but instead of taking the time to write out those routes, let's instead learn about rest and resourceful routes first. Because I think that's a better option.


image.png

image.png

image.png
  • controller的名称前缀通常用复数,一个model对应一个controller
 ~/simple_cms$ rails generate controller Subjects index show new edit delete
class SubjectsController < ApplicationController
  def index
  end

  def show
  end

  def new
  end

  def create
  end

  def edit
  end

  def update
  end

  def delete
  end

  def destroy
  end
  
end

Rails.application.routes.draw do
  get 'subjects/index'
  get 'subjects/show'
  get 'subjects/new'
  get 'subjects/edit'
  get 'subjects/delete'
  root 'demo#index'

  get 'example/index'
  get 'demo/index'
  get 'demo/hello'
  get 'demo/other_hello'
  get 'example/other_hello'
 
  # get 'demo/baidu'

  #default roots, may be gone away in future
   # get ':controller(/:action(/:id))'

  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

REST

What is REST?

  • Representational State Transfer 代表层状态转换
  • Do not perform procedures 不需要执行程序
  • Perform state transformations upon resources·根据资源执行状态转换

REST Paradigm Requirements(REST范式要求)

  1. Organize code into resources
    • Encourages one controller for each model
  2. Learn HTTP verbs for working with resources
    • Determine which CRUD actions are suited for each verb
  3. Map a new URL syntax to controller actions
    • Change Rails routes
  4. Modify existing links and forms to use new URL syntax
    - Use resourceful URL helpers
    image.png
  • 在REST中POST只用于update项目


    image.png

    image.png

Resourceful routes

Why use resourceful routes?

  • Rails default
  • Optimized for REST
  • Simple, consistent, organized structure
  • Improves application security
  • Most professional Rails developers use them.


    image.png

    image.png

    默认没有删除的操作

    image.png

    image.png
resourceful routes examples
maxiaoan:~/simple_cms$ rails routes
                   Prefix Verb   URI Pattern                                                                              Controller#Action
                     root GET    /                                                                                        demo#index
           delete_subject GET    /subjects/:id/delete(.:format)                                                           subjects#delete
                 subjects GET    /subjects(.:format)                                                                      subjects#index
                          POST   /subjects(.:format)                                                                      subjects#create
              new_subject GET    /subjects/new(.:format)                                                                  subjects#new
             edit_subject GET    /subjects/:id/edit(.:format)                                                             subjects#edit
                  subject GET    /subjects/:id(.:format)                                                                  subjects#show
                          PATCH  /subjects/:id(.:format)                                                                  subjects#update
                          PUT    /subjects/:id(.:format)                                                                  subjects#update
                          DELETE /subjects/:id(.:format)                                                                  subjects#destroy
               demo_index GET    /demo/index(.:format)                                                                    demo#index
               demo_hello GET    /demo/hello(.:format)                                                                    demo#hello
         demo_other_hello GET    /demo/other_hello(.:format)                                                              demo#other_hello
       rails_service_blob GET    /rails/active_storage/blobs/:signed_id/*filename(.:format)                               active_storage/blobs#show
rails_blob_representation GET    /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show
       rails_disk_service GET    /rails/active_storage/disk/:encoded_key/*filename(.:format)                              active_storage/disk#show
update_rails_disk_service PUT    /rails/active_storage/disk/:encoded_token(.:format)                                      active_storage/disk#update
     rails_direct_uploads POST   /rails/active_storage/direct_uploads(.:format)                                           active_storage/direct_uploads#creat

Resourceful URLs helps

image.png

image.png

image.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,063评论 6 510
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,805评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,403评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,110评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,130评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,877评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,533评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,429评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,947评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,078评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,204评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,894评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,546评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,086评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,195评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,519评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,198评论 2 357

推荐阅读更多精彩内容