1
2

More than 3 years have passed since last update.

Rails の scope 便利手帳

Last updated at Posted at 2019-12-23

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") }

その他追記予定

1
2
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
1
2