0
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メソッドとクラスメソッドでnilを返す時の挙動が違う

Posted at

##クラスメソッドの場合

class Book
  def self.published
    where(published: true)
  end
end

Book.published.order(id: :desc)
#=> Attendance Load (3.8ms)  SELECT `attendances`.* FROM `attendances` WHERE `attendances`.`date` BETWEEN '2022-01-01' AND '2022-01-31' ORDER BY `attendances`.`id` DESC

nilの場合はnilが返るのでメソッドチェーンが使えない。

class Book
  def self.published
    nil
  end
end

Book.published
#=> nil

Book.published.order(id: :desc)
#=> NoMethodError: undefined method `order' for nil:NilClass

##scopeの場合

class Book
  scope :published, -> { where(published: true) }
end

Book.published.order(id: :desc)
#=> Attendance Load (3.8ms)  SELECT `attendances`.* FROM `attendances` WHERE `attendances`.`date` BETWEEN '2022-01-01' AND '2022-01-31' ORDER BY `attendances`.`id` DESC

nilの場合でもallメソッドが実行されるのでメソッドチェーンが使える。

class Book
  scope :published, -> { nil }
end

Book.published
#=> nil

Book.published.order(id: :desc)
#=> Attendance Load (3.8ms)  SELECT `attendances`.* FROM `attendances` WHERE `attendances`.`date` BETWEEN '2022-01-01' AND '2022-01-31' ORDER BY `attendances`.`id` DESC

##参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?