今週のrailscasts - Advanced Queries in Rails 3
Railscasts - Advanced Queries in Rails 3を見て。今週のrailscasts - Active Record Queries in Rails 3 - maeshimaの日記の続き的な内容。
クラスメソッドとscopeの組み合わせ
引数とるタイプのscopeはクラスメソッドで定義した方が見やすい(もしかしたら違うこと言ってたかも)。で、定義したクラスメソッドをscopeで使う時には順番に注意する必要がある。
scope :cheap, cheaper_than(5) def self.cheaper_than(price) where("products.price < ?", price) end
だとエラーになる
def self.cheaper_than(price) where("products.price < ?", price) end scope :cheap, cheaper_than(5)
これならおk
merge
下記のような感じで "&" を "かつ" として使える!!!
Category.joins(:products) & Product.cheap
build
下記のような感じでscopeの条件に合うオブジェクトをnewできる。これってRails2のnamed_scopeでもできなかったっけ?
Product.scope_name.build
arel
arelはARとsqlの間を取り持つ的なプラグイン。arelを直接いじって簡潔に書くみたいな話をしてたような気がする。
Product.arel_table
でarel的なオブジェクトを取得。下記のような感じで使う。
t = Product.arel_table t[:price].eq(2.99) t[:name].matches("%catan").to_sql
MetaWhere
sql的な文字列を極力排除するためのプラグイン。
Article.where(:title.matches => 'Hello%', :created_at.gt => 3.days.ago) => SELECT "articles".* FROM "articles" WHERE ("articles"."title" LIKE 'Hello%') AND ("articles"."created_at" > '2010-04-12 18:39:32.592087')
感想
今回のはちょう参考になったので何度か見直してものにしておきたい。