Rails 5 was a major release
with a lot of new features
like Action Cable, API Applications, etc.
Active Record attribute API was
also one of the features of
Rails 5 release which did
not receive much attention.
Active Record attributes API is
used by Rails internally for a long time.
In Rails 5 release, attributes API was made
public and allowed support for custom
What is attribute API?
Attribute API converts
the attribute value to an appropriate Ruby type.
Here is how the syntax looks like.
The first argument is the name of the attribute
and the second argument is the cast type.
Cast type can be string, integer
or custom type object.
Before using attribute API,
movie ticket price was a float value, but
after applying attribute on price,
the price value was typecast as integer.
The database still stores the price as float and this
conversion happens only in Ruby land.
Now, we will typecast movie release_date
from datetime to date type.
We can also add default value for an attribute.
Let’s say we want the people to rate
a movie in percentage. Traditionally, we would
do something like this.
With attributes API we can create a custom
type which will be responsible
to cast to percentage rating to
number of stars.
We have to define the cast method in the custom type
class which casts the given value to the expected output.
The attributes API also supports
where clause. Query
will be converted to SQL by calling
serialize method on the type object.