How to define and test a hash attribute in a Rails ActiveRecord model- 3 mins
To persist a hash in an ActiveRecord model, you can utilize the hstore extension for PostgreSQL. Rails 4 allows you to define columns of type
hstore which utilize the hstore extension.
hstore is supported by PostgreSQL 9.2+.
To effectively define and test a model with a hash attribute, we can follow the steps outlined below:
- Enable the hstore extension
- Add the hash column to the model
- Configure model to use hstore extension
- Create spec and define assertions for the attribute
- Add validation for attribute to model
To enable hstore, you must issue the CREATE EXTENSION command.
In a PostgreSQL script or shell:
This command can also be executed via a Rails migration:
Add the hash column to the model
Create a migration to add the hash column to your model. In this example, we’ll be defining the
meta column of the
post model as a hash:
Note the use of
hstore as the column type.
Configure the model to use the
We have to identify the
meta column on the
Article model with
We can test the meta column in the Rails console:
The factory makes use of the factory_girl gem:
If test the model, we should receive a failure message:
This happens because we have not added the necessary validation to the
Post model. We’ll do that in the next step.
Add validation for attribute to model
To enable our model test pass, we add the required validation:
The tests should pass now.
We should note that
hstore stores all values as strings. The values should be casted to their appropriate types before use.
What does this have to do with robots?
Not much, really.