rails-scope
scope はモデルに付加できる、予め決められた検索条件、もしくは動的に設定できる検索条件。
例えば、いつも検索する時に必要な固定条件がある場合や、必ず何かしらの条件を設定して検索するような場合に、毎回Where()やconditionsなどを生成する手間を省略できる。
>|ruby|
class Hoge < ActiveRecord::Base
scope :notInDeleted, where('deleted_at is null')
scope :searchTitle, lambda {|t| where("titles.name like '%?%'", t) }
end
||<
としておくと、
>|ruby|
res1 = Hoge.notInDeleted
res2 = Hoge.searchTitle('hoge')
||<
などとできる。
勿論where()だけでなくorder()やselect()も使える。
また、
>|ruby|
res = Hoge.notInDeleted.searchTitle('hoge)
||<
のように、メソッドチェーンも可能。
これは便利。