Skip to content

Instantly share code, notes, and snippets.

@arosh
Created August 29, 2012 09:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arosh/3509466 to your computer and use it in GitHub Desktop.
Save arosh/3509466 to your computer and use it in GitHub Desktop.
activerecord with sqlite3, another primary key
source :rubygems
# activerecordにはパッケージ名に罠がある
# http://stackoverflow.com/questions/4016929/bunder-require-does-not-work-for-activerecord-in-my-gem
gem 'activerecord', require: 'active_record'
gem 'sqlite3'
require 'bundler'
# Gemfileに指定したGemをrequireする
Bundler.require
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: 'database.db'
)
class User < ActiveRecord::Base
# set_primary_key :twitter_id と設定せよ、という情報がWEB上で散見されるが、
# 現在ではdeprecatedになっている
self.primary_key = :twitter_id
validates :twitter_id, presence: true
end
# 実験用なので、とりあえずDBの中身を空にしておく
User.destroy_all
# newはインスタンスを作るだけ(後でsaveが必要)
# createはインスタンスの作成とsaveを両方行ってくれる
=begin
ハッシュを引数に取る記法もあるが、
残念ながらエラーが出る
User.create(twitter_id: "hoge", bar: "baaar!!")
=end
User.create do |u|
u.twitter_id = "hoge"
u.bar = "baaar!!"
end
fuga = User.new do |u|
u.twitter_id = "fuga"
u.foo = "f"
u.bar = "b"
end
fuga.save
# 主キーが"hoge"であるレコードを取ってくる
p User.find("hoge")
require 'bundler'
# Gemfileに指定したGemをrequireする
Bundler.require
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: 'database.db'
)
# "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL を自動で作らない
ActiveRecord::Migration.create_table :users, id: false do |t|
t.string :twitter_id, null: false
t.string :foo
t.string :bar
# created_atとupdated_atを自動で作成
t.timestamps
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment