ActiveRecord をRailsなしで使う方法 / How to use ActiveRecord without Ruby on Rails.

接続

LocalhostMySQLのsandboxデータベースにユーザー:'test'、パスワードなしで接続

ActiveRecord::Base.establish_connection(
	:adapter => 'mysql',
	:host => 'localhost',
	:username => 'test',
	:password => '',
	:database => 'sandbox'
)

ログ

debug.logにクエリログとかを保存

ActiveRecord::Base.logger = Logger.new("debug.log")

テーブルの作成

class名にこまる

class HogeTables < ActiveRecord::Migration
 	def self.up
		create_table :tests do |t|
			t.column :id, :string
			t.column :user_name, :string
			t.column :contents, :string
		end
	end
	def self.down
		# アンインストール時はに作ったテーブルを消す。
		drop_table :tests
	end
end
HogeTables.migrate(:up)

テーブル操作とか

testsテーブルのデータをActiveRecord objectに。

class Test < ActiveRecord::Base
end
テーブルが存在するか確認

testsテーブルがあるか確認するには

Test.table_exists? # 存在すればtrue
データ挿入
test=Test.new(
	:id => 'user01',
	:user_name => 'hoge',
	:contents => 'ふがふが'
)
test.save