back to

The Rails 4 Way

ARCHIVED

Archived: This project has been archived. Cards can no longer be completed.

Working with Controllers

Alejo
Alejo completed this card.
Last updated
Remove all business logic from your controllers and put it in the model. (My) instructions are precise, but following them requires intuition and subtle reasoning. 
— Nick Kallen

The heart of a rails applications is its controllers, because whenever someone connects to your application (via a URL), what they're doing is asking the application to execute a controller action.

Controllers are tightly linked to the views, much more so than to the controllers. This is because each time a controller action is requested, (usually) a view is rendered. This view can be of different formats e.g. JSON, HTML, XML, JS.

Rack

Rack is a modular interface for handling web requests, written in Ruby, with support for many different web servers. It abstracts away the handling of HTTP requests and responses into a single, simple call method.  The call method should return a 3-element array consisting of the status, a hash of response headers, and finally, the body of the request.

hello world as a Rack app.png 90.07 KB


Rack is relevant to Rails controllers because much of ActionController is implemented as Rack middleware modules.

Action Dispatch

Controller and View code in Rails is packaged as a part of the Action Pack framework. As of Rails 3, dispatching of requests was extracted into a component of Action Pack called Action Dispatch, and it contains the classes that interface the rest of the controller system to Rack.

When your application receives a request, it is received by ActionDispatch::Routing::RouteSet, the object on which you call draw in routes.rb. The route set chooses the rule that matches, and calls its Rack endpoint.

So what a route like get 'foo', to: 'foo#index' is called, the dispatcher's call method executes FooController.action(:index).call.

In this case, the index action in the FooController receives the call and what it does is try to render the template in views/foo/index.html. This is because Rails controller actions have an implicit render method on it, that in this case would be: render "foo/index".

Following convention over configuration, Rails will always call the template in a view folder named like the controller, and look for a file with the name of the controller action. However, if you ever want to do something different, just call render "something/different" in any controller action, and it will send looking for that template.

Controller/View Communication
Controllers hand-off data pulled from the models to the views. In Rails, this is done through instance variables.