逆引きActiveRecord

RailsActiveRecord、非常に便利なしくみではあるのだが、使いこなすには常にそこから生成されるSQL文を意識する必要がある。生成後のSQL文をイメージしたあとでActiveRecordのコーディングを考えることもしばしば、、、。
ならば、ということでActiveRecordから生成されるSQLの逆引き辞典を作ってみることにしました。

  • SELECT * FROM posts
Post.find(:all)
  • SELECT * FROM posts WHERE id = 1
Post.find(1)
  • SELECT * FROM posts WHERE user = 1
Post.find(:all, :conditions => 'user = 1')
  • SELECT * FROM posts WHERE project_id = 1
class Project < ActiveRecord::Base
  has_many :posts
end
Project.find(1).posts.find(:all)
  • SELECT id FROM posts
Post.find(:all, :select => 'id')
  • SELECT * FROM posts ORDER BY date
Post.find(:all, :order => 'date')
  • SELECT * FROM posts ORDER BY date DESC
Post.find(:all, :order => 'date DESC')
  • SELECT * FROM posts LIMIT 10
Post.find(:all, :limit => 10)

とりあえず初回はこれだけ