Think In Geek

In geek we trust

Fixtures and serialized attributes in Ruby on Rails

If you’ve ever used the serialize method in an ActiveRecord model, you may have faced the problem of writing a fixture for that particular serialized field. The serialize method is quite handy if you need to store a complex object (like a Hash or an Array) in a database field, without having to create additional models and relationships between them. A good example could be store the preferences of a user in a hash:

class User < ActiveRecord::Base
    serialize :preferences, Hash

This way you can set and get the preferences attribute of the user without having to worry much about it:

User.first.preferences # => {:show_email => true, :allow_pm => :false, ...}
user = User.first
user.preferences = {:show_email => true, :allow_pm => :false}

In order to do that, at the database table for the User class, among the other fields you’ll need to add a text column for the preferences. After that, you can easily work with your model without too much of a hassle.

If you care to look at the rows of the model’s table, you’ll see that the serialized attribute is stored in YAML format:

sqlite> select preferences from users where id = 1;
:show_email: false
:allow_pm: false

Now, that if you need to add a fixture for your model that needs the preferences attribute to be set to a particular value? If you have to manually parse the value you want to put in there to be tested, it’ll be a pain in the ass. Even if you have a script that converts certain values to YAML so you can copy and paste the script output to the fixture, it’s not very comfortable. Hopefully, you have to remember that you can use some ERB magic in your fixtures :) So, here’s the deal if you need to add something to the serializable attribute:

  preferences: <%= {:show_email => true, :allow_pm => :false}.to_yaml.inspect  %>

The to_yaml method converts the Hash into a YAML representation, and with inspect we convert that to a string. Using this technique, we can add whatever we want to a serialized field in our fixtures.


, , , ,

2 thoughts on “Fixtures and serialized attributes in Ruby on Rails

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>