maeshimaの日記

メモ書きです

今週のrailscasts - Active Record Queries in Rails 3

Railscasts - Active Record Queries in Rails 3

基本的には、findメソッドに渡すハッシュキーがそのままメソッドになる。

# Article.find(:all, :order => "published_at desc", :limit => 10)
Article.order("published_at desc").limit(10)

例外はconditionsとinclude

# Article.find(:all, :conditions => ["published_at <= ?", Time.now], :include => :comments)
Article.where("published_at <= ?", Time.now).includes(:comments)

基本はall。firstやlastは明示的にメソッドとして使う必要がある。

# Article.find(:first, :order => "published_at desc")
Article.order("published_at").last

first

lazy loading

Article.order("name") #=> relational objectが返ってくる。まだクエリは投げない

named_scopeの変更

下記のような感じになった

scope :visible, where("hidden != ?", true)
scope :published, lambda { where("published_at <= ?", Time.zone.now) }
scope :recent, visible.published.order("published_at desc")

scope内で他のscopeの名前も渡せる!!!

to_sql

puts Article.recent.to_sql # クエリ

to_sqlメソッドでsqlクエリを表示してくれる!

感想

めちゃ便利になったみたい