Ruby on Rails で、使いやすいScopeをまとめました。
Model の設計によって差異があるものの、視点は使えるのでは?と思います。
Scopeとは
Model に scope を記載することで、Controllerなどから、複雑なWhere条件を書かずにデータを取りだせるようになります。
app/model/article.rb
class Article < ApplicationRecord
scope :newer, ->{order("updated_at DESC") }
end
これによって、Controllerなどで
app/controllers/articles_controller.rb
@articles = Article.newer
で、更新日が新しい順に取得することができます。
app/controllers/article.rb
@articles = Article.newer.limit(5)
とすると、更新日が新しい順に5件を取得できます。
公開されているか
scope :published, -> { where(published: true) }
ある時間より前か
scope :created_before, ->(dt) { where("created_at < ?", dt) }
呼び出し元では、引数に時間をいれる
@articles = Article.created_before(Time.now)
予約時間が過ぎたものであるか
scope :reserved, ->{where("reserve_at < '#{Time.zone.now}'") }
現在時刻以下
終了状態であるか
終了日の有無で判定する場合
scope :finished, ->{where("finished_at IS NOT NULL") }
その他追記予定