Skip to content

Instantly share code, notes, and snippets.

@mahemoff
Last active December 14, 2017 02:00
Show Gist options
  • Save mahemoff/dbd33b0a34ff21cc8787 to your computer and use it in GitHub Desktop.
Save mahemoff/dbd33b0a34ff21cc8787 to your computer and use it in GitHub Desktop.
Rails - Turn empty strings into nil before validation
class ApplicationModel < ActiveRecord::Base
# http://stackoverflow.com/questions/1183506/make-blank-params-nil
class_attribute :null_attrs
self.null_attrs = %w( )
def nil_if_blank
self.class.null_attrs.each { |attr|
self[attr] = nil if self[attr].blank?
}
end
end
class Book < ApplicationModel
self.null_attrs = %w(title author)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment