Importing data into a Rails application
There will come a time when you need to import data into your Rails application. Our time was now. We needed to move some data from a PHP based forum into a shiney new Rails application using Eldorado for it’s forums (this fortunately followed a very similar schema) – which means nice shiney ActiveRecord models. We were provided a mySQL backup of the existing forums so off we went.
So where to start – well at first glance it seemed like it was going to be troublesome but it turns out it’s not that bad thanks to ActiveRecord. First up, we need to create a connection to a mySQL server – we’ll do this via database.yml (fortunately you can have multiple db connections per application);
# database.yml legacy: adapter: mysql database: host: 127.0.0.1 username: password:
Then we essentially needed to ‘ActiveRecord-ify’ the legacy models coming from the mySQL database – fortunately ActiveRecord makes this super simple. So we created a Legacy:Base class which extended ActiveRecord base classes;
# legacy.rb class Legacy::Base < ActiveRecord::Base self.abstract_class = true establish_connection "legacy" end
The we simply created legacy models for each model in the mySQL database extending our legacy base class – the only thing these needed to know was the name of the table they corresponded to – just to make sure ActiveRecord was happy. (It turns out that our tables used an ‘id’ column akin to AR so didn’t need to explicitly set this on each model)
... # legacy.rb class Legacy::ForumCategory < Legacy::Base set_table_name 'forum_categories' #set_primary_key 'id' end
This now meant we could do the following in script/console;

By extending the legacy base class which extended ActiveRecord our legacy models get full ActiveRecord support rolled into them – so it’s then super simple to iterate over the data and create a new model object for use in the new application, populate the object and then save it. And of course, since it’s ActiveRecord we don’t care what the target database is.
In the end, we created a rake task to create a repeatable process for importing the users from the DB – which also allowed us to handle any situations where the data we were trying to insert into our new models was failing validation.
No related posts.


