LoginSignup
0
0

ActiveRecord scopeについて

Posted at

scope とは

クエリを定義できるもの
よく使うものであったり、変数的に命名したいものを定義できる
引数を渡すこともできる

class Post < ApplicationRecord
  scope :published, -> { where(published: true) }
  scope :recent, ->(days_ago = 7) { where("created_at >= ?", Time.now - days_ago.days) }
end

クラスメソッドとの使い分け

条件分岐など、ロジックが複雑になりそうなものに関しては、クラスメソッドを定義する

class Post < ApplicationRecord
  def self.recent(days_ago = 7)
    where("created_at >= ?", Time.now - days_ago.days)
  end
end
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