DEV Community

Cover image for Using Value Objects in Ruby on Rails

Using Value Objects in Ruby on Rails

Vinicius Porto on April 01, 2023

In this article, we explore the concept of Value Objects in Ruby on Rails and how they can be used to encapsulate business logic and improve the ma...
Collapse
 
andreimaxim profile image
Andrei Maxim

In contrast, a Rails Model is a more complex object that represents a database table and includes functionality for querying and updating the associated records.

There really isn't anything about the app/models folder that forces you to store there only objects that inherit from ActiveRecord. That folder is actualy meant as a home for all types of models, regardless if they are backed up by a database table or not.

Obviously, if you feel like it makes more sense for you or your team to put value objects in a separate folder, like you did in that example.

Collapse
 
feliperaul profile image
flprben

Really great article.

It would be nice if you could add a section on serialize with a custom coder, which seems to be a valid approach as well (see gorails.com/episodes/custom-active...).

It looks to me that serialize with a custom coder can achieve pretty much the same as the attribute with a custom ActiveRecord::Type.

The composed_of, however, has the added benefit of being able to create a value object that (as the name implies) is composed of multiple columns of the model, instead of a single one, so it's more versatile.