Database Operations with Class Methods

Learn how class methods should be used in the database operations of our Rails application.

Database manipulation in Rails

If we look at the class methods that are provided by Rails (excluding the DSL methods previously discussed), they all center around providing ways of accessing the underlying database. This is a good guide for the types of methods we should add. But we would recommend only adding methods to facilitate reuse. Another way to say this is to add class methods to the Active Record only if both of these criteria hold:

  • There is a need for the method’s logic in more than one place.
  • The method’s logic is related to database manipulation only and not coupled to business logic.

Let’s see an example. Suppose widgets can have one of three statuses: “fresh”, “approved”, and “archived”. Fresh widgets require manual approval, so we might write some code like this in a background job that emails our admin team for each fresh widget they should approve:

Get hands-on with 1200+ tech skills courses.