Using MVC thinking to understand the design structure of the Ruby on Rails framework, rubyrails
In rails, the process of sending a request (/users) is as follows:
1). the browser sends a request (/users)
2) Rails routes requests to the index method of users_controller.
3) users_controller calls the User Model back to obtain all the users
4) The User Model reads all the users from the database,
5) The User Model encapsulates all the users read from the database as a List and returns it to user_controller.
6) user_controlle assigns the User list returned by the user Model to the instance variable @ users, which is passed to the index view.
7) The index view receives the passed @ users and renders the view as HTML through embedded ruby.
8) user_controller returns the rendered page to the browser.
Different request processing processes are basically the same. Except for routing policies, that is, calling different controllers or different methods of controllers is determined by Rails Router.
Rails Router
The routing policy for resources in Rails fully complies with the REST design style, that is, the URL is only responsible for locating resources, and the operations on resources are determined by the native HTTP Method type, only in routes. configure resources: users in rb to obtain the following routing policies:
HTTP request URI Action Purpose GET /users index page to list all users GET /users/1 show page to show user with id 1 GET /users/new new page to make a new user POST /users create create a new user GET /users/1/edit edit page to edit user with id 1 PUT /users/1 update update user with id 1 DELETE /users/1 destroy delete user with id 1
Of course, in addition to the REST-style routes, Rails also supports various customized routes rules by adding statements in routes. rb as follows:
match 'user/create' => 'users#new', :via => :get
This rule matches browser browsing/user/create. Rails routes requests to the new method of users_controller. Other processing methods are the same as/users/new. However, Rails uses the first matching rule. If we change the preceding route statement
match 'users/create' => 'users#new', :via => :get
It will not work as we imagined, and it will match the rules
GET /users/1 show page to show user with id 1
,
Obtain the user whose id is created.