rubyでRailsなしでActiveRecordを使う

DBの環境


Homebrewで構築した、ローカルのMySQL5.1


テーブルはこんな感じのを用意

CREATE TABLE stations (name CHAR(255), info TEXT, FULLTEXT(info) WITH PARSER mecab);
mysql> CREATE TABLE stations (name CHAR(255), info TEXT, FULLTEXT(info) WITH PARSER mecab);
Query OK, 0 rows affected (0.01 sec)

mysql> desc stations;
+-------+-----------+------+-----+---------+-------+
| Field | Type      | Null | Key | Default | Extra |
+-------+-----------+------+-----+---------+-------+
| name  | char(255) | YES  |     | NULL    |       |
| info  | text      | YES  | MUL | NULL    |       |
+-------+-----------+------+-----+---------+-------+
2 rows in set (0.00 sec)

使い方

# -*- encoding: utf-8 -*-
require 'rubygems'
require 'active_record'

#DBに接続
ActiveRecord::Base.establish_connection(
            :adapter  => 'mysql2',
            :username => 'root',
            :password => '********',
            :host     => 'localhost',
            :database => 'test',
            :encoding => 'utf8'
        )

# テーブル用のクラスを用意
class Station < ActiveRecord::Base
end

# 1個データを作ってsaveしてみる
station = Station.new
station.name = '入間市駅'
station.info = '解説文'
station.save

# 検索
Station.find(:all).each{|s|
  puts s.name # "入間市駅" が出力される
}

ハマったこと

adapterをmysqlにしていたらエラーになった
`rescue in mysql_connection': !!! Missing the mysql2 gem. Add it to your Gemfile: gem 'mysql2' (RuntimeError)


Rails3では、mysql2をアダブターにしているので修正する

mysql2をインストールする時に警告が発生する
$ gem install mysql2

WARNING: This version of mysql2 (0.3.11) doesn't ship with the ActiveRecord adapter bundled anymore as it's now part of Rails 3.1
WARNING: Please use the 0.2.x releases if you plan on using it in Rails <= 3.0.x

ActiveRecordでは、0.2.x を入れる必要があるらしい


バージョンを指定して、mysql2 を入れる

$ gem install mysql2 -v 0.2.6