Heroku経由でSinatraを使ってみているのですが、ModelとしてSequelを使ってみることにしました。 Userクラスを作る DBをオンメモリにしておいて、テーブル作成・クラスの宣言 1 % irb 2 require 'rubygems' 3 require 'sequel' 4 5 DB = Sequel.sqlite 6 DB << "CREATE TABLE users (id INTEGER PRIMARY KEY, name VARCHAR(255) not NULL)" 7 8 class User < Sequel::Model 9 end 1 User.create(:name => 'satoko') 2 3 User.find(:name => 'satoko') 4 User.find(:id => 1).update(:name =
dataset = DB[:users].join(:items, :user_id => :id).find(:items__id => 5) こんな構文を書いたときで、userテーブルにもitemテーブルにも同一名カラムidがあったとする。 こんなときは上記の書き方ではSQL文として SELECT * FROM USER INNER JOIN ITEM ON ITEM.user_id = USER.id WHERE ITEM.id = 5 こんな感じに展開されて、idがうまく取れない。うまく取る方法が知りたい。。。 解決策の1つとして、graphを使うというのがあるみたい。 dataset = DB[:users].graph(:items, :user_id => :id).find(:items__id => 5) こう書くとSQL文上では*の部分が全部展開されて SELECT U
普通にschema pluginを使ってモデルを定義していましたが、 リファレンスを見るとschemaはテスト向けの変更の予定が無いDB向けで、 普通はmigrationを使ってね、と書いてありました This plugin is mostly suited to test code. If there is any chance that your application’s schema could change, you should be using the migration extension instead. Sequel: The Database Toolkit for Ruby Sequel::Plugins::Schema PLAIN TEXT RUBY: # db/migrate/001_create_posts.rb class CreatePosts <S
Rubyにおける軽量なデータベースツールキットとして、なかなかお手軽なSequelですが、実際に使うにあたっていくつか悩んだポイントがあったので、備忘録としてその解決法をメモしておきます。 なお、この記事はRuby 1.9.1p378とSequel 3.8.0の組み合わせを対象として書いています。 モデルの定義前にDB接続をしたくない SequelにもActiveRecordパターンに基づいたモデルの仕組みが用意されていますが、「モデルを定義した時点でデータベースへの接続が存在していなければならない」という制約があります。 つまり、 require 'sequel' Sequel.connect('sqlite://test.db') class User < Sequel::Model; end p User.all は動きますが、 require 'sequel' class User
Objecttank@rubyのDBアクセスライブラリをDBIからSequelに移行中。Sequelの参考ページhttp://sequel.rubyforge.org/http://www.slideshare.net/zhesto/ruby-off-rails-japanesehttp://xxx.mostevildanceclassics.com/page/r/SequelRubyインストール sudo gem install sequel とりあえず実行sequelのコマンドラインツール。railsのscript/consoleのようなもの。 sequel mysql://user:password@localhost/dbname DBという名前の変数に接続オブジェクトが格納されるテーブル名=userがあったとすると、、、 DB[:user].filter(:id => 10).a
シンプルな実装。 モデルクラスが必須ではなく、あるテーブルを表すオブジェクトを経由してDB操作を行う。 デザインパターンは、Table Data Gatewayに対応。 標準添付のSequel::Modelによって、モデルクラスを使うことも可能。 マイグレーション用のコマンドラインツールが付属。 モデルを使わない場合 require 'rubygems' require 'sequel' # DB接続 DB = Sequel.sqlite('book-sq.db') # スキーマ作成 unless DB.table_exists?(:books) DB.create_table(:books) do primary_key :id string :title integer :year end end # データの作成 DB[:books].insert(:title => "初めてのRu
キーボードを、持ち歩く。 久しぶりに、スマホ用のキーボードを使ってブログを書いている。 いくつかキーが壊れてしまっているので買い替えないといけないのだが、壊れるくらいには使い込んでいたんだなと思った。 当時は、今のようにPCを普段から持ち歩くことが少なかったので、出先でもブログ…
リリース、障害情報などのサービスのお知らせ
最新の人気エントリーの配信
処理を実行中です
j次のブックマーク
k前のブックマーク
lあとで読む
eコメント一覧を開く
oページを開く