← Back to Upcase

Self v. scoped for anonymous ActiveRelation scopes


(Dan Croak) #1

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?


(Joe Ferris) #2

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.


(Dan Croak) #3

Nice. Thanks, Joe. I hearted your reply.