ActiveRecord and MySQL Setup on Ubuntu 12.04.1

As a .Net developer I thought I would give Ruby and ActiveRecord a try for a simple web application. When I say simple I mean it’s only two operations. One consists of non-authenticated data entry and the other of data retrieval. Install of everything went fine, or so I thought. It turns out that there are some intricacies in getting the right activerecord to work on Ubuntu.

This is a quick blog post of getting activerecord to work with MySQL on Ubuntu 12.04.1 LTS. This is a result of me searching a bunch of other blogs and tutorials to figure out what I was doing wrong.

Getting the files

>sudo apt-get install mysql-server
>sudo apt-get install ruby
>sudo apt-get install rubygems
>sudo gem install activerecord
>sudo apt-get install libmysqlclient15-dev
Note: this may install “libmysqlclient-dev” instead, which should be fine.
>sudo gem install activerecord-mysql2-adapter

You should now have all the required files.

Setup test database

Connect to MySQL and create a database and table.

>create database dummy;
>use dummy;
>create table tests(id bigint primary key auto_increment, text varchar(100));

A test ruby file: atest.rb

#! /usr/bin/ruby
require ‘rubygems’
gem ‘activerecord’, ‘=3.2.9’
require ‘active_record’

class Test < ActiveRecord::Base

ActiveRecord::Base.establish_connection( :adapter => ‘mysql2’,
  :host => ‘localhost’,
  :username => ‘username’,
  :password => ‘password’,
  :database => ‘dummy’

Record = Test.create(:text => ‘new record text’)
Inserted_records = Test.where(:id => 1)
# It is recommended to use “find” instead of “where“ when selecting by the primary key.
# I used where as a test to make sure I had everything installed and working
Puts inserted_records[0].text

Make sure you have a reference to the gem in your ruby file. If you don’t, when you go to use the ”where” method you will receive a method_missing error. As of writing, the active record gem version was 3.2.9.
Also make sure the adapter in the establish_connection method is ‘mysql2’. Using the older ‘mysql’ adapter will also cause issues.


I did skip creating a new user and granting access to the mysql database as that was an easy web search.