DEV Community

loading...

Rails Backend: Initializing an instance with a default value

Sylwia Vargas
I teach React, Redux, JavaScript, Ruby, Rails at Flatiron School | I care about web accessible and inclusive tech | she/her
・1 min read

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

Discussion (0)