named_scopeについて
環境
- Rails
- 3.0.8
確認用モデル生成
author
$ rails g model author name:string
book
$ rails g model book author:references title:string price:integer
author:referencesで生成するとBookモデルはbelongs_to :author ができます。
class Book < ActiveRecord::Base belongs_to :author end
モデルのnamed_scope
author
class Author < ActiveRecord::Base scope :name_is, lambda {|n| where :name => n} end
book
class Book < ActiveRecord::Base belongs_to :author scope :cheaper_than, lambda {|p| where 'price <= ?', p} scope :written_by, lambda {|name| joins(:author) & Author.name_is(name)} end
- &はmerge()のエイリアス
できること
Book.cheaper_than(1000).written_by('david').to_sql => "SELECT \"books\".* FROM \"books\" INNER JOIN \"authors\" ON \"authors\".\"id\" = \"books\".\"author_id\" WHERE \"authors\".\"name\" = 'david' AND (price <= 1000)"