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
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
Top comments (0)