rails increment counter model
class Counter < ApplicationRecord
def self.increment_counter(name, amount = 1)
counter = find_or_initialize_by(name: name)
counter.value ||= 0
counter.value += amount
counter.save
counter.value
end
end
Explanation for each step:
class Counter < ApplicationRecord
: Defines a class namedCounter
that inherits fromApplicationRecord
, which is commonly used in Ruby on Rails to interact with the database.def self.increment_counter(name, amount = 1)
: Defines a class methodincrement_counter
. It takes two arguments:name
(the name of the counter) andamount
(the value by which the counter will be incremented, defaulting to 1 if not provided).counter = find_or_initialize_by(name: name)
: Tries to find aCounter
record in the database with the givenname
. If it doesn't exist, it initializes a newCounter
object with the providedname
.counter.value ||= 0
: If thecounter
object'svalue
attribute isnil
or falsy, it sets it to 0. This ensures that thevalue
attribute has a numeric value before incrementing.counter.value += amount
: Increments thevalue
attribute of thecounter
object by the specifiedamount
.counter.save
: Saves the changes made to thecounter
object in the database.counter.value
: Returns the updatedvalue
of thecounter
after incrementing.