LoginSignup
7
1

More than 3 years have passed since last update.

railsのクラスメソッドとscopeの違い

Last updated at Posted at 2019-12-16

クラスメソッドとscopeの違い

Rails5.2までのガイドには以下の記述がありましたが実際は全く違います。
Rails6.0から記述が削除されています。

This is exactly the same as defining a class method, and which you use is a matter of personal preference:

訳: スコープでのメソッドの設定は、クラスメソッドの定義と完全に同じ (というよりクラスメソッドの定義そのもの) です。どちらの形式を使用するかは好みの問題です。

scope

基本的にActiveRecord::Relationを返す。

class User < ApplicationRecord
  scope :royal, -> { find_by(royal: true) }
end

scopeの結果がnilの場合.allの結果が返る

$ User.find_by(royal: true)
=> nil

$ User.count
=> 100

$ User.royal == User.all
=> true

nilを返さないのでscopeをメソッドチェインして使える

正し、以下の場合はnilを返す。

scope :empty, -> { [] }

クラスメソッド

nilを返すのでメソッドチェインして使うとNoMethodErrorが発生する可能性がある

参考

nilを返すケース

warningを入れるか、raiseするかの検討PR

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