Self v. scoped for anonymous ActiveRelation scopes

I’ve seen class methods that act as scopes use self or scoped for conditionals where their SQL should not be chained:

def self.search(query)
  if query.blank?
    self
  else
    where('name @@ ?', query)
  end
end

or:

def self.search(query)
  if query.blank?
    scoped
  else
    where('name @@ ?', query)
  end
end

Is there anything wrong with the self version? What could go wrong?

One difference is that ActiveRecord classes are not Enumerable, but scoped returns an ActiveRecord::Relation, which is.

That means that you can call things like map(&:name) when scoped is used but not on self.

2 Likes

Nice. Thanks, Joe. I hearted your reply.