Attributes
attributes acts as a way to add a typecast layer to a model. The attribute may be backed by a database column, or it can be a "transient" attribute that only exists for the lifetime of a model instance.
Also see store_model.

Use cases

Structured JSON

JSON columns can be very lightweight and flexible ways to represent data when you are not sure exactly what you schema will look like in the future, and can be a way to defer decision making until more information is known. Adding a custom type and an attribute to represent a JSON column can provide more robustness.
This can look like this:
1
# In some model...
2
attribute :my_custom_attribute, Attributes::MyCustomAttribute.new
Copied!
1
# The "bridge" between the attribute definition and the custom attribute type
2
class Attributes::MyCustomAttribute < ActiveRecord::Type::Json
3
def deserialize(value)
4
return value unless value.is_a?(String)
5
6
parsed = JSON.parse(value)
7
8
if parsed.blank?
9
return MyCustomAttribute.new
10
end
11
12
MyCustomAttribute.new(**parsed.symbolize_keys)
13
end
14
15
def serialize(value)
16
value&.to_json
17
end
18
end
Copied!
1
# An ActiveModel-enabled class that can run validations, define custom comparators, etc.
2
class MyCustomAttribute
3
include ActiveModel::Model
4
include ActiveModel::Validations
5
6
# ...definitions
7
end
Copied!

Sources