Ruby Hack: A Quick Way to Update Existing DB table in Ruby on Rails

AnnMargaret Tutu
3 min readApr 27, 2017

I’m a JavaScript lover and really love the flexibility that unstructured technologies like Meteor JS and MongoDB afford when it comes to storing data. SimpleSchema lives up to it’s name and makes adding optional structure a cinch.

Occasionally though (not too often), I leave the nest and tinker with other languages/stacks that adhere more strictly to the MVC architecture.

I had to dip into an open source Ruby on Rails codebase (somewhat legacy), for example, and realized how many more intermediary steps (commands and all) there were when setting up data models for a Rails app.

Coming from Meteor JS/JavaScript, even running a simple migration can slow me down.

I get horrendous gibberish like this when I run commands intended for more up-to-date versions of Rails:

Luckily, I discovered a quick hack that seems to be version-agnostic.

Say you have an existing “users” table that looks like this, in your schema.rb:

If you run the following command in your terminal:

$ rails g migration AddFieldsToUsers

Followed by the new columns you want to add, so the full command looks like this:

$ rails g migration AddFieldsToUsers firstname:string lastname:string company:string telephone:string address:string city:string state:string zip:string

You’ll see that this successfully generates a new migration record, sans headache

And your schema table now looks like this:

Why did that work?

The command “AddFieldsToUsers” has hidden superpowers of the highest mercy baked in.

  • “Add” => start generating a migration and define a new change method within it:
  • Fields => Just an arbitrary single-word place holder for the new columns we pass as parameters. This would have worked if I had used something like “AddDonutsToUsers”, for example.
  • ToUsers => The schema table we want to update — to “users”.

Basically, AddFieldsToUsers breaks down to => add a new migration record with a change method that updates my users schema with these new fields I’m about to mention.

Last we run:

$ rake db:migrate

And if we take a peek at which fields are accessible to the User class in our rails console, we get:

$ [1] pry(main)> User.columns.map {|c| c.name}=> ["id","email","referral_code","referrer_id","created_at","updated_at","firstname","lastname","company","telephone","address","city","state","zip"]

And that’s it. Hope this hack helps someone!

--

--

AnnMargaret Tutu

Research Software Engineer (ML, DL, Blockchain, Android), budding cryptologist, writer and aspiring polymath.