💎 Ruby on Rails
Advanced
What is the difference between class methods and instance methods in ActiveRecord?
Answer
In ActiveRecord, class methods are called on the model class itself and typically return a relation or perform bulk operations: User.active (scope), User.count, User.create(...). They are defined with def self.method_name or inside class << self. Instance methods are called on a specific record object: user.full_name, user.save, user.destroy. Knowing this distinction matters for scopes (always class methods returning relations), callbacks (instance methods called on the object), and association methods. A common mistake is accidentally calling a class method on an instance or vice versa, which raises a NoMethodError.
Previous
What are Rails engines and how are they used?
Next
What is optimistic vs pessimistic locking in Rails?
More Ruby on Rails Questions
View all →- Advanced What is metaprogramming in Ruby/Rails and give examples?
- Advanced What is the difference between include, extend, and prepend in Ruby?
- Advanced How does Rails handle database connection pooling?
- Advanced What is Rack and how does Rails relate to it?
- Advanced What is query optimization with explain in Rails?