Controllers (see UnderstandingMVC for an overview) tie the model (database, business objects and processes) to the view (user interface).
Accessing the model is simple; it’s just a collection of classes. Interacting with the view is more complicated in concept, as webapp frameworks tend to have a strict interface between the model and view that feels more like configuration than programming. However, Rails makes it very simple.
One simple way to define Rails controllers: controllers are the only part of MVC that must be defined. That’s because the model only provides data and processes (the controller can provide that if you want, or do without it), and the controller can also generate output without relying on an separately-defined view.
To demonstrate this, here’s the code for a minimal Rails app that tells you the current time.
class TimeController < ApplicationController
def now
render :text => "The time is #{Time.now}."
end
end
A model by itself does nothing; a view in isolation is utterly useless; but a controller is entirely self-sufficient if the application is very simple. (Or very inelegant!)
There are more details in UnderstandingRailsMVC, but what we have here is a time controller, with a now action, such that when the user visits http://your-app.com/time/now, the method defined above will be called, and their browser will display “The time is Fri Apr 22 02:17:17 GMT+10:00 2005” or similar.
See also:
category: Understanding