When a model has associated logic or attributes that are used exclusively for creating a representation of the model—as in HTML for a website or JSON for an API endpoint—a best practice is to avoid storing those values directly on the model.
Storing view-specific attributes on the model can create confusion about what is truth (stored in the database) and what is purely representational. View Objects, then, act as an adapter between the truth and the representation of the truth.
For example, the truth of an imagined inventory item is that the
price attribute stored in the database is
599 cents. But the representation for the product page may be a mutation of the truth, such as
It would be inappropriate to store the representational data as a secondary price attribute on the model. It would be even worse to inject the formatting logic into the template.
What View Objects do is dress up the data, by way of transforming, adding, or removing data properties, returning a new object for use in the presentation layer. This approach creates a nice home for our presentation-specific logic and attributes, keeping it removed from the model truth.Read More