LoginSignup
0
0

More than 3 years have passed since last update.

【Rails】scopeを使う

Last updated at Posted at 2020-03-06

DB問い合わせでよく使う条件を、モデルのscopeに登録することができる。

scopeなし

@active_users = User.where(status: 1).order(id: :desc)

scopeを使う

model
class User < ApplicationRecord
  scope :active, -> { where(status: 1).order(id: :desc) }
controller
@active_users = User.active

scopeに引数を渡す

model
class User < ApplicationRecord
  scope :status, -> (num) { where(status: num) }
controller
@active_users = User.status(1)
@not_active_users = User.status(0)

合わせ技

model
class User < ApplicationRecord
  scope :status, -> (num) { where(status: num) }
  scope :recent, => (int) { order(id: :desc).limit(int) }
controller
#@recent_active_users = User.where(status: 1).order(id: :desc).limit(10)
@recent_active_users = User.status(1).recent(10)

参考

0
0
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
0
0