freks blog

about

Railsのscopeでnilになる場合はallが返る

created: 2018-12-18

Railsで勘違いしていたのでメモ

class Post < ActiveRecord::Base
  scope :by_author, -> author { where(author: author) }
end

みたいなコードがあるときに

post = Post.by_author('Sample')

で、Sampleというauthorがいない場合、nilが返ってきそうだけど、allで返ってくる

参考) ActiveRecord scope with first returns all records · Issue #13647 · rails/rails

バグを出してしまったので注意する

This site is managed by freks