When working with Rails, we are familiar with ActiveRecord. Active Record is the Model in the MVC framework that is the layer of the system responsible for representing business data and logic. It’s an ORM that connects the rich objects of an application to tables in a relational database management system.
We come across cases where classes in Rails require model-like features, but they are not tied to any table in a database. That is where Rails ActiveModel comes into picture. It’s a library used in developing classes that need some features present on Active Record.
Let’s say we have a
Person class with
We want to add validations to these attributes.
ActiveModel we can implement
Person class as below:
When we include
ActiveModel::Model we get some features like:
- Model name introspection
Any class that includes
can be used with Action View helper methods like
render just like we do with Active Record objects.
Before Rails 7,
ActiveModel::Model works as the minimum API to
talk with Action Pack and Action View.
the Model name suggests it can be included to
create Active Record type models.
ActiveModel::Model does not support
the basic common functionality
Let’s take the below example to see where the
attribute: method fails.
To resolve the above issue,
we need to include
ActiveModel::Attributes in the Person class.
ActiveModel::API will now keep its definition to a minimum when talking with
Action Pack and Action View.
ActiveModel::Model can then be extended in the future to add more
functionality that resembles ActiveRecord’s Model.
ActiveModel::Model now only include
It enables the addition of more functionality to the Model while
keeping things backward compatible.