Action Pack: The View and Controller

Get familiar with the Rails view support in this lesson.

We'll cover the following

Generally, the view and controller parts of MVC are intimately connected. The controller supplies data to the view, and the controller receives events from the pages generated by the views. Because of these interactions, the support for views and controllers in Rails is bundled into a single component called Action Pack.

Don’t be fooled into thinking that our application’s view code and controller code will be jumbled up because Action Pack is a single component. Quite the opposite is true, actually, as Rails gives us the separation we need to write web applications with clearly demarcated code for control and presentation logic.

View support

In Rails, the view is responsible for creating all or part of a response that is displayed in a browser, processed by an application, or sent as an email. At its simplest, a view is a chunk of HTML code that displays some fixed text. More typically, we’ll want to include dynamic content created by the action method in the controller.

In Rails, dynamic content is generated by templates, which come in three flavors. The most common templating scheme, called Embedded Ruby (ERB), embeds snippets of Ruby code within a view document. In many ways, this is similar to other web frameworks such as PHP or JavaServer Pages (JSP). Although this approach is flexible, there are concerns that it violates the spirit of MVC. By embedding code in the view, we risk adding logic that should be in the model or the controller. As with everything, judicious use is healthy while overuse can become a problem. Maintaining a clean separation of concerns is part of the developer’s job.

We can also use ERB to construct JavaScript fragments on the server that are then executed on the browser. This is great for creating dynamic Ajax interfaces.

Rails also provide libraries to construct XML or JSON documents using Ruby code. The structure of the generated XML or JSON automatically follows the structure of the code.

Get hands-on with 1200+ tech skills courses.