LoginSignup
13
13

More than 5 years have passed since last update.

scopeの引数の渡し方

Last updated at Posted at 2014-08-13

scopeの醍醐味、それはメソッドの再利用にあります。
が、しかし、scope内にがっつり具体的な引数を渡してしまってはなかなか使い回せません。

*デフォルト引数を渡して例外をなくすという使い方もありますが、今回はとにかく一つのメソッドを出来るだけ、汎用性の高いものにすることを目的としました。

scopeに抽象的な引数を渡し、様々なクラスで使えるようにしたい!
ということで、scopeの引数の定義の方法を記します。

hoge.rb
scope :date, -> date { where(date: date)}

{}の外に引数の種類を記すことが重要です。
てか、それだけです笑

これで、引数がdate型であれば様々な箇所で使うことができます。

hoge_controller.rb
@hoge = Hoge.date(params[:date])

でも

hoge_controller.rb
@hoge = Hoge.date(@hoge.date)

でも使える。

基本中の基本ですが、今回非常に役に立ちました。

13
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13