Rails Routes & Controllers
- Explain the basics of an HTTP request-response cycle
- Explain how the request-response cycle works with respect to Rails & MVC
- Explain what a RESTful API is
- Build Rails Routes, Controllers & Actions corresponding to the 7 RESTful routes
What is a server?
- The term ‘server’ is used to refer to both software and hardware.
- Speaking in terms of software, the server is what runs all the code of your application. Most often, servers follow a request-response pattern where it is constantly ‘listening’ for requests, and then uses the application code to create or serve a response to the client(machine that made the request). The client and server communicate via a network, but we don’t need to get to into that — for now the internet will still be a black box that is magically able to make machines in remote locations communicate with each other.
- As mentioned, the term ‘server’ is also oftentimes used to refer to the actual machine running the application code. I think the software definition is more important to think about since it gets to the heart of what a server really is (code that can serve the end user what it is requesting) and since machines are often used to run multiple processes (they usually aren’t dedicated servers whose only job is to run the server software).
- Keep this definition in mind later when we talk about the Rails Server.
What happens when you go to
google.com and hit
- This is one of the most classic interview questions in the web development industry. (The real answer includes
Load Balancers, etc.)
- Here’s the basic process:
- Browser checks local cache for a matching DNS record to get an IP address
- If address not in local cache, checks OS, then dispatches a DNS query if still not found
- The Browser then initiates TCP connection with server using this IP address
- The Browser sends HTTP request to server (GET www.google.com page)
- The Server handles request and sends back response w/ status code
- When we make our request this
httpgets added to the front of the URL - does anyone know what HTTP is?
- HyperText Transfer Protocol
- Underlying protocol used by the World Wide Web that defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands.
- We could talk about HTTP for a long time. In short, HTTP involves a Request and Response between a Client (aka your Macbook) and a server (aka your Rails App)
- Client makes some request, and the server either creates a side-effect, or gives you a resource back (commonly HTML, but it doesn’t have to be)
HTTP Request Basics
- Comprised of: Request Line
- Method (HTTP Verb) (e.g.
- Path (e.g.
- Query String (e.g.
?loc=san+francisco- optional) 如何使用？怎么往url上加key val？
- Headers (e.g.
- Body (e.g.
- Note that these are the only portions we are focused on today, we’ll get more into HTTP when we do Rails Lite.
- The method, or HTTP Verb defines what type of action is being performed. They’re pretty self-explanatory, and we’ll talk about them more in a second.
- The path defines what resource we are looking for.
- The body and query string provide any extra information we may need.
HTTP Methods (CRUD)
PUT) patch together就是检测服务器的时候了。有可能会发生碰撞。服务器检测，通过了就通过了，通不过就不通过。
- When we think about the core actions we need to be able to perform on an application resource, it’s really only these 4 things. We need to be able to read information from the DB so we can display it, add new things to the DB, update existing things, and delete things. That’s it — that’s what CRUD is.
- Common question: “What’s the difference between
PUT?" A: The answer is only mildly interesting, so I encourage you to google that on your own time :) https://medium.com/backticks-tildes/restful-api-design-put-vs-patch-4a061aa3ed0b
Parts of a URL
- Discuss how we make an HTTP request to a domain and that everything that comes after the domain is what we call the path. Often, students are confused the difference between a URL and a path. Explain how the routes we write in our app are simply paths that are relative to the domain. Let them know that we aren’t putting our apps on the internet yet so we’ll be using
localhostwhich is a domain for our own machine's IP (which is always
- REST is a set of design principles for making network communication more scalable and flexible.
- Explain the RESTful routes and how they work. REST is a way of mapping HTTP verbs (
DELETE) and CRUD actions (create, read, update, delete) together in a semantic way. Explain what the wildcard
:idis and why we need it on certain routes, and not on others. Explain that these routes are URI patterns combined with HTTP verbs, and that the controller action hit is based on the pattern matched. Anything with a wildcard has infinitely many URIs that could match it - if we made a
GET /photos/9request they would both hit the
photos#showaction but for two different photos. It would match the
GET photos/:idroute, and the request would have parameters containing a key value pair of
id: 9, respectively.
- Note that we won’t be using the
#editactions today -hese actions are specifically used to get a form to create a new resource or update an existing resource, but since we don't know HTML yet and can't make forms we wont' be doing that. You should hit home on the point that
createin the same way
editare both responsible for getting forms that will trigger either
update, respectively, upon submission.
- Bonus question, what does REST stand for?
- REST — Representational State Transfer
Website vs. Web Service (API)
- Web Service is meant for machine to interface with — needs data that can be used/manipulated (JSON, XML, YAML, etc.)
- Websites are meant for human interaction, whereas web services are meant for machine interaction
- We haven’t gotten to the View layer yet (the V in MVC) so we will use Rails as a web service for now and instead just return response in the form of data. JSON is the most common data-interchange format and we’ll be working a lot with it later, so we’ll use that for now but don’t worry too much about what it is at this stage.
Example requests to RESTful API
GET /usersquery all users
GET /users/1query for user with ID 1
POST /userscreate a new user
PATCH /users/1update user with ID 1
DELETE /users/1delete user with ID 1
- Here’s an example of some requests that would hit our RESTful routes. Note that we’ve replaced the wildcard
:idwith actual ids. Explain how this would playout again (even if you just explained on the previous slide, doesn't hurt to quickly re-iterate with an example in front of their face)
GET /usersgets the users.
GET /users/1gets the user with id 1.
Can these two routes co-exist?
Note: The URI pattern is the same, with two different wildcards. These routes essentially collide with each other as both will match the same pattern (e.g.
GET /users/1 and
GET /users/gerald would each be matched by both routes - there's no way for us to know whether the thing after the second slash is an id or a username immediately)
- Status (e.g. 200, 302, 404)
- Headers (e.g.
- Body (e.g. actual HTML document)
- Common Response Codes
- So we have dispatched our request, its been interpreted by our router, and now its time for our server to send back its response.
- A response has 3 key components — status, headers and body.
- Status indicates whether the request was successful or not
- Headers include metadata about the response like what the format of the response is
- The body contains the actual data/content the server responded with. This could be the HTML for our website, or maybe a JSON object containing data.
- There is also a link here to describe all status codes. Some of the more common are 200 for OK, or 404 for not found. Take some time during today’s project to take a read through this. Status 418 is a favorite.
GET /users in Rails App
- Last week we discussed the Model. As we know, the model is what handles all of our database logic
- In otherwords, our CRUD logic (how we create, read, update, and destroy items inside of our database)
- But, we know that isn’t enough for a website. In the end, we want a user to click ‘Sign Up’, and then somehow through some sort of witchcraft, that user gets inserted in our database with
ActiveRecord. Eventually, I want to click “Like” on a chirp, and I want that like to somehow be recorded.
- That is all done through something called the Request Response cycle, and that’s what today’s lecture is all about.
ROUTER : Takes in HTTP Requests, decides where to send them, instantiate an instance of controller and invokes an action on that controller
Controllers: Take in HTTP Requests, decides what to do with them & how to respond
Hash-like Ruby Object which contains information about the HTTP request
Three ways to pass params in an HTTP request as follows:
- Using wildcards inside a route (e.g.
- Via the query string (e.g.
- Inside the request body (usually built using a form, basically a bunch of key value pairs)
- Should avoid for
- Explain that these are three ways you can pass up data with an HTTP request. The body is usually used to pass up data for a
PATCHrequest, that we want to add or update in our DB. We'll see examples of using each in the demo.
add gem: gem ‘better_errors’gem ‘binding_of_caller’ # only in developmentconfig/routes.rb#verb 'path' to: 'controller#action' as alias_nameget "chirps", to: "chirps#index"brrbrr -c chirps # see the only one create chirps_controller.rbcreate ChirpsController classcreate Chirps#indexdef index
chirps = Chirp.all
render json: chirps #不能有两个render，也不可能有render json 和 redirect，那样就没意义了。
end可以在rails 的method里面放debuggerdef index
debugger chirps = Chirp.all
render json: chirps
end这个时候就得在跑起来的时候去检查terminal 看debug 信息了
routes.rbget '/chirps', to: 'chirps#index'
get '/chirps/:id', to: 'chirps#show'
post '/chirps', to: 'chirps#create'
patch '/chirps/:id', to: 'chirps#update'
delete '/chirps/:id', to: 'chirps#destroy'
endresources :name_of_resources, only:/except: [:method_name, :another_method]chirps = localhost/chirps
chirp_url(1) => localhost:3000/chirp/1
chirp_url(chirp ID 是 1 的那个instance) => localhost:3000/chirp/1
Setting up Routes
- Generate 7 standard RESTful routes for a resource:
- resources :users
- Can add
exceptoption to include/exclude certain actions
- resources :users, only: [:create, :destroy]
- resources :users, except: [:create, :destroy]
- Create a custom route in
- get ‘/users’, to: ‘users#index’
- Explain the various ways we can create routes in Rails.
- Explain the difference between
except, in the example above
onlywill give us the 2 routes specified, and
exceptwill give us the 5 routes not specified
Setting up Controllers
- Generate a controller in terminal :
rails g controller users
- If created manually, be sure to define your class as below:
- class UsersController < ApplicationController end
- Generate a model in terminal :
rails g model user
- Roll back a generated controller or model, in terminal :
rails d model <model_name>
rails d controller <model_name>
- Add a JSON extension to make reading JSON responses easier e.g. JSON Formatter
redirect new http request
render not a new request, just render pictures.