5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

sqlite3をactiverecordから使ってみる

Posted at

背景

某ツールでユーザ操作に簡易DBを使いたかったのでsqlite3を使ってることにした。
普段はrailsを触る機会が多いので、active_recordから使ってみた。
メモがてら投稿。

インストール

$ cat Gemfile
source "https://rubygems.org"

gem 'sqlite3'
gem 'activerecord'

$ bundle install

使い方

test_sqlite3_by_activerecord.rb
ADAPTER = 'sqlite3'
DBFILE  = 'test.sqlite3'

# DB接続
ActiveRecord::Base.establish_connection(adapter: ADAPTER, database: DBFILE)

# テーブル作成
ActiveRecord::Migration.create_table :users do |t|
  t.string  :name
  t.string  :email
  t.timestamp :created_at, :null => false
end

# Userモデル
class User < ActiveRecord::Base; end

# User操作
user = User.new
user.name  = "testuser"
user.email = "test@example.com"
user.save
User.all.count  #=> 1
user = User.all.first
user.destroy
User.all.count  #=> 0

# テーブル削除
ActiveRecord::Migration.drop_table :users

# DB削除 (ファイル削除)
File.delete(DBFILE)

# DB切断
ActiveRecord::Base.connection.disconnect!

実行結果

$ ruby test_sqlite3_by_activerecord.rb
-- create_table(:users)
   -> 0.2466s
-- drop_table(:users)
   -> 0.1665s
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?