class Post < ApplicationRecord scope :latest_post, ->(user_id) do where(user_id: user_id).last end end Post.latest_post(1) =>すべてのレコードが返る
Post.where(user_id: user_id)
でnilが返る場合scopeはallを返すような挙動になるので注意。
where
で該当レコードがない時は空のActiveRecord::Relationが返る。
find_by
で該当レコードがない場合はnilが返るので、その場合全てのレコードが返る。