Created
April 5, 2018 16:15
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage: