DEV Community

Sylwia Vargas
Sylwia Vargas

Posted on

Rails Backend: Initializing an instance with a default value

Imagine we are building a quiz app and we'd like all users to start out with 0 points. We can achieve it with a number of ways, one of which would be setting a default value to the user instance.

1. In the User class, create init method

This method will set the default value only if it's nil:

  def init
    self.points = 0 if self.points.nil?
  end
Enter fullscreen mode Exit fullscreen mode

2. Trigger the init method after initialization

Add an after_initialization method at the User class. Now your code should look as follows:

class User < ApplicationRecord
  after_initialize :init

  def init
    self.points = 0 if self.points.nil?
  end

end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)