Arvind singh
Arvind singh

Reputation: 1402

Why would you use a scope when you could use regular Ruby class methods?

Scopes

class Comment < ActiveRecord::Base
  scope :most_recent, -> (limit) { order("created_at desc").limit(limit) }
end

using scope

@recent_comments = Comment.most_recent(5)

Class Methods

In Model

def self.most_recent(limit)
  order("created_at desc").limit(limit)
end

In controller

@recent_comments = Comment.most_recent(5)

Why would you use a scope when you could use regular Ruby class methods?

Upvotes: 3

Views: 90

Answers (1)

oreoluwa
oreoluwa

Reputation: 5633

I think the biggest reason to use scopes is because it would always return an ActiveRecord::Relation, even if the scope evaluates to nil unlike the class method. You can also add specific methods to a scope which are not going to be present in the class unless the scope is called.

scope :lovely, -> name { where(name: name) if name.present? }

this would return the collection if there is no name. But in class method, you would have to do something like this

def self.lovely(name)
  if name.present?
   where(name: name)
  else
   all
  end
end

You can find more documentation of scopes here: Active Record scopes vs class methods and here: Should You Use Scopes or Class Methods? and ActiveRecord::Scoping::Named::ClassMethods

Upvotes: 1

Related Questions