Rails: What's the difference between lambda, scope and class method? What's best practice?

Viewed 4866

The code snippet has three methods: lambda, scope and class method.

All of them returns the same results.

Questions:

  1. Is there any best practice in Ruby/Rails when it is preferred to use one over the other ?
  2. In what cases would you use lambda, scope or class method ( best practices ).

    class Cars < ActiveRecord::Base     
      attr_accessible :manufacturer, :price, :used
    
      #one
      scope :used_and_cheap_lambda, lambda { where('used = ?', true ).where('price >= ?',30000) }
    
      #two
      scope :used_and_cheap_scope, where('used = ?', true ).where('price >= ?',30000)
    
      #three
      def self.used_and_cheap_class
        where('used = ?', true ).where('price >= ?',30000)
      end
    end
    
    
    
    
    
    Cars.used_and_cheap_lambda.count
    => #24
    
    Cars.used_and_cheap_class.count
    => #24
    
    Cars.used_and_cheap_scope.count
    => #24
    
4 Answers
Related