Controller Patterns and CRUD

Controller Patterns in a Datacentric App

So far we've seen each action in our controller doing the following two things:

  1. Interacting with the database, either read data from the database (with a SELECT SQL statement) or write data to the database (with INSERT, UPDATE or DELETE SQL statements)

  2. Use the retrieved data to render a view template (in case of a "read"), or redirect to a different page (in case of a "write")

If the request wants a HTML document back (in case of HTTP GET), it retrieves the data from the database then uses it to render a dynamic view template into a HTML document, which it then uses to set up the HTTP response; if the request wants to update data in the database, it collects the user's input, prepares the data, uses it to compose a SQL statement to change the database, then setup the HTTP response.

The controller stands between the data (in the database) and the presentation (the view templates) to coordinate the flow. This is a fundamental pattern of controllers that we'll see repeatedly in Rails applications.

CRUD

Before we move on, there's one more interesting thing to note: at this point, we've built out what is known as CRUD functionality for our simple blog application

CRUD stands for:

  • C - create
  • R - read
  • U - update
  • D - delete

CRUD represents four basic actions to interact with data. The four resource actions here map directly to SQL's four core commands: INSERT, SELECT, UPDATE and DELETE. In fact, our current Rails application is essentially a web front that collects user's input and delegates the data manipulation to the underlying database. Sometimes people call these type of apps "CRUDy" apps or "data centric" apps, where the web application's concerns are centered around interacting with the database.