以下の記事は、調査の結果現状のRuby on Rails
では期待通りに動かないことがわかりました。
Rails-2.1の新機能であるnamed_scopeを使うと、従来のwith_scope
では綺麗にかけなかったスコープの選択を簡潔に記述することができます。
rails>>
def gadgets_on_sidebar(place = 'index')
case place.to_s
when 'index'; Gadget.on_index
when 'show'; Gadget.on_show
else Gadget.all
end.with_scope{active_gadgets + Gadget.mandatories}
end
<<--
各スコープメソッドは、ActiveRecord::NamedScope::Scope
オブジェクトを返すので、
これを条件にしたがって選択し、最後に.with_scope
を呼んでスコープを適用します。
そこで、
with_named_scope
というGemプラグインをつくり、
上述のように処理できるようにしました。
以下のようになります。
rails>>
def gadgets_on_sidebar(place = 'index')
case place.to_s
when 'index'; Gadget.on_index
when 'show'; Gadget.on_show
else Gadget.all
end.with{active_gadgets + Gadget.mandatories}
end
<<--
ということで、Rails本家にもpatchを送っておきました。
posted by
genki on Fri 1 Aug 2008 at 16:06 with 3 comments
目下調査中です。
[Improved named_scope to be used like as with_scope ](http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/739)