Mind Dump, Tech And Life Blog
written by Ivan Alenko
published under license Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)copy! share!
posted at 14. Jul '17

ActiveRecord Callbacks Notes

after_commit runs also on destroy action

If something specific is done after a database insert, update or delete, it can be limited.

after_commit :generate_nice_uri, :on => [:create, :update]

and

after_commit :delete_home_directory, :on => [:destroy]

set default values to the model with after_initialize

In Ruby on Rails. In other classes, like standard Ruby class, use the method def initialize().

require 'securerandom'

class Note < ActiveRecord::Base
  after_initialize :set_defaults, :set_defaults2

  def set_defaults
    # empty strings
    self.title = 'Unknown title!' if self.title.blank?

    # nil numbers (or fresh unsaved record)
    # this doesn't handle empty string values from a blank form input
    self.quota ||= 204800

    # automatically cull values whether is comes from database or user
    @radius = 1 if @radius < 1
    @radius = 999 if @radius > 999

    # DOING IT WRONG WAY
    #
    # BEWARE: this sets new UUID in every INSTANTIATION (load)!
    self.uniqueid = SecureRandom.uuid

    # the correct way
    self.uniqueid ||= SecureRandom.uuid
    # or (handy if not using strip_attributes gem)
    self.uniqueid = SecureRandom.uuid if self.uniqueid.blank?

    # you probably don't want this
    # sets always quota to 20800, so .save will propagate this into the database
    self.quota = 20800
  end

  # or set default this way, if using a database
  def set_defaults2
    if !self.persisted? # for new record
      @quota = 204800
      @max = 99999
    end
  end
end

Add Comment