Rails4 scopeでActiveRecordを簡潔に

ActiveRecordを簡潔に書くことができるscopeのメモ。


scopeの定義

class User < ActiveRecord::Base
  scope :created_before, ->(datetime) { where("created_at < ?", datetime) }
end

scopeはクラスメソッドのようにも、インスタンスメソッドのようにも使える。

# クラスメソッドのように使う
User.created_before(DateTime.now)

# インスタンスメソッドのように使う
user.created_before(DateTime.now)


scopeは複数組み合わせることができる

class User < ActiveRecord::Base
  scope :created_before, ->(datetime) { where("created_at < ?", datetime) }
  scope :order_id, -> { order(:id) }
end

使い方

# クラスメソッドのように使う
User.created_before(DateTime.now).order_id

# インスタンスメソッドのように使う
user.created_before(DateTime.now).order_id


参考:
Active Record Query Interface — Ruby on Rails Guides