named_scopeの引数による条件分岐

named_scopeに引数を渡した場合、その型によって設定するSQLを動的に変更したいことがある。 こういうときにはlambdaに渡しているのブロック中で条件分岐すれば良い。


named_scope :member, lambda { |m|
  case m
  when Member
    { :conditions => { :member_id => m.id } }
  when Integer
    { :conditions => { :member_id => m } }
  else
    {}
  end
}

要するに、lambdaに渡したブロックの処理の結果、findに渡すHashパラメータが返ればそれでok、という感じなんじゃないかと。


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <img localsrc="" alt="">