Arelを使ってみよう
さて,
例えば,
books.
create table authors(id integer primary key autoincrement not null, name varchar); create table books(id integer primary key autoincrement not null, title varchar, price integer, published_date date, author_id integer);
執筆時現在の最新バージョン
require 'rubygems'
require 'arel'
require 'sqlite3'
require 'active_record'
ActiveRecord::Base.configurations = {'development' => {:adapter => 'sqlite3', :database => 'books.sqlite3'}}
ActiveRecord::Base.establish_connection('development')
Arel::Table.engine = Arel::Sql::Engine.new(ActiveRecord::Base)
books = Arel::Table.new :books
puts books.to_sql
これを実行すると,
出力されるSQL
SELECT "books"."id", "books"."title", "books"."price", "books"."published_date", "books"."author_id" FROM "books"
それでは,
books = Arel::Table.new :books
books = books.where(books[:title].eq('Head First Rails'))
puts books.to_sql
出力されるSQL
SELECT "books"."id", "books"."title", "books"."price", "books"."published_date", "books"."author_id" FROM "books" WHERE "books"."title" = 'Head First Rails'
以下のように,
books = Arel::Table.new :books
authors = Arel::Table.new(:authors).where(authors[:name].eq('david'))
books = books.join(authors).on(books[:author_id].eq(authors[:id]))
books = books.where(books[:price].gt(3000))
books = books.order(books[:published_date])
books = books.take(10)
puts books.to_sql
出力されるSQL
SELECT "books"."id", "books"."title", "books"."price", "books"."published_date", "books"."author_id", "authors"."id", "authors"."name" FROM "books" INNER JOIN "authors" ON "books"."author_id" = "authors"."id" WHERE "books"."price" > 3000 AND "authors"."name" = 'david' ORDER BY "books"."published_date" ASC LIMIT 10
このように,
このRelationはあくまで
このおかげで,
これこそまさに,
Arelはこのようにして,