Skip to content

Instantly share code, notes, and snippets.

@gduquesnay
Created April 5, 2018 16:15
Show Gist options
  • Save gduquesnay/f0283f2a760deaf7b5956904ee7d9715 to your computer and use it in GitHub Desktop.
Save gduquesnay/f0283f2a760deaf7b5956904ee7d9715 to your computer and use it in GitHub Desktop.
Workaround for Persisting an empty string in an integer field with a default value converts to nil #32467
# see: https://github.com/rails/rails/issues/32467
# written with help from: https://github.com/noise-machines
# sponsored by: https://www.hiresuccess.com/
require "active_support/concern"
module ReplaceNilsWithColumnDefaults
extend ActiveSupport::Concern
included do
before_save :replace_nils_with_column_defaults
end
module ClassMethods
attr_reader :columns_to_replace
private
def only_replace_nils_for(*columns_to_replace)
@columns_to_replace = columns_to_replace.map(&:to_s)
end
end
def replace_nils_with_column_defaults
columns_to_replace = self.class.columns_to_replace || attributes.keys
attributes.slice(*columns_to_replace).each do |column, value|
default = self.class.column_defaults[column]
self[column] = default if value.nil?
end
end
end
@luca-aurelia
Copy link

Sample usage:

class Test < ApplicationRecord
  include ReplaceNilsWithColumnDefaults
  only_replace_nils_for :time_limit
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment