Matthew Lindfield Seager

Matthew Lindfield Seager

Model View Controller and Rails Apps

Model View Controller (MVC) is a design pattern in which an application’s code is divided by responsibility.

The “Model” refers to the underlying objects and code that represent (model) the business processes and logic. This includes the actual business objects themselves, stored data, schemas (including relationships, constraints/validations and indices) and operations specific to manipulating and storing the data. In a Rails app this usually consists of model objects, each of which inherits from ActiveRecord, the schema and migrations.

The “View” refers to the parts of the application a user sees and interacts with. Pages, forms, tables, visualisations, feeds and summaries all form part of the view layer. In a Rails app the user usually interacts with HTML pages (with supporting CSS and JS) but other “views” of the application could include JSON/XML feeds or APIs. In Rails, these various views are often delivered using ERB templates & partials and the supporting assets are delivered using Sprockets and Webpack/Webpacker.

The “Controller” is responsible for mediating between the Model & the View and between the user & the application as a whole. In a Rails app the former is accomplished with “controllers”, which inherit from Action Controller, while the latter is handled by the routes file and routing system. Additional responsibilities usually handled at the Controller layer include caching and session management.

Some of the benefits of separating these responsibilities include the ability to test and refactor different parts in isolation, the option to reuse objects or even use the same Model (backend) with different Views (e.g. a web app, a RESTful API and an iOS app) and better designed interfaces which make for easier collaboration within (or between) teams.