1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Railsのscopeとは

Posted at

scope(スコープ)とは

特定のSQL文をメソッドのように呼び出すことができる機能のことです。

下記のように、モデル内にscopeを定義することで使用することができます。

hoge_hoge.rb
class HogeHoge < ApplicationRecord
  scope :active, -> { where(deleted: false) } 
  scope :by_account, -> lambda{|account_id|where(account_id: account_id)}
end
# 使用例
HogeHoge.active

HogeHoge.by_account(params[:account_id])

HogeHoge.by_account(params[:account_id]).active

何が便利なのか?

・コードが短くなる。

・適切なscope名をつけることで、直感的に読みやすいコードになる。

・何度も同じようなクエリを使いまわしている場合、
 scopeを使用していれば、一箇所修正するだけで済む。

参考記事:

https://pikawaka.com/rails/scope
https://qiita.com/ozin/items/24d1b220a002004a6351
https://qiita.com/ngron/items/14a39ce62c9d30bf3ac3

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?