Controllers & HTTP - acanyon/RubyTuesdays-ConnectFour GitHub Wiki

Controllers

Controller: gets any data that the page (view) needs to display from the database, responds to things that the user does (like click save)

The way the controller figures out which method to call is through the route used to access it.

A route in rails looks like this: GET /games/:id(.:format) games#show

In the browser, this looks like this: http://localhost:3000/games/1. Take a look at config/routes.rb to see the rest of them. (if you want to make your URLs prettier, this happens in routes.rb - for example to change users/new to users/signup)

  • The first part of the route (GET) is the type of HTTP request that the application is expecting with this route (more on HTTP later).
  • The second part (/games/:id(.:format)) is how it's going to look in the URL. The :id that you see is a parameter that the browser is expected to pass through (in this case, it's expecting the id of a Game in the database). You can access parameters in the controller with params[:id].
  • The last part (game#show) is telling you what controller method is going to be called. In this case, the show method in the games_controller will be called. When that method is called, it returns an HTTP response that has the view in it and any data. The view that rails uses is the same as the controller method - in this case it uses views/games/show.html.haml.

Writing controller methods

Basic controller methods are surprisingly simple. There's a piece of rails magic here - instance variables in the controller are available in the corresponding view (instance variables are referenced with an at sign, like @game). So for example, if you want to have a list of games available in your view, in your controller method you could have the line @games = Game.all. Rails has a simplified query language

HTTP methods & status codes

HTTP (hypertext transfer protocol) is the basics of the internet. The only HTTP methods we need to talk about for the game controller are GET, POST, and DELETE.

  • GET is the most common method and does about what it sounds like - it gets some content from the server and returns it to the browser.
  • POST sends data back to the server that we want to save - it's the method that is called if you make edits to form and click 'submit'.
  • And DELETE is also pretty straightforward. It passes a record back to the server and tells it to delete it from the database.

HTTP status codes are returned as part of the response header from the controller and indicate to the browser how everything went.

  • A code of 200 means the request occurred without error.
  • 201 means that the method was created without error.
  • 404 is pretty familiar, and means the URL could not be found.
  • A 400 status means the request had bad syntax.

Further reading