Empty scope in Rails 4 with `none`

Rails 4 introduced the none query method which allows you to chain ActiveRecord query methods on an empty array. Imagine you have a method posts_for_user which is implemented as follows:


def posts_for_user(user)
  return [] if user.nil?
  return Post.where(user: user)
end

The problem is that ActiveRecord query methods are not chainable on the empty array []. The solution to this is the none query method (see http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-none for the doc):


def posts_for_user(user)
  return Post.none if user.nil?
  return Post.where(user: user)
end

Nice solution for a often recurring problem, especially if you apply defensive programming techniques.

Write us your thoughts about this post. Be kind & Play nice.