Skip to content

Instantly share code, notes, and snippets.

@dougcole
Created March 20, 2014 07:10
Show Gist options
  • Save dougcole/9658739 to your computer and use it in GitHub Desktop.
Save dougcole/9658739 to your computer and use it in GitHub Desktop.
Handle empty strings with ActiveRecord
module NilifyBlanks
def nilify_blanks(*columns)
columns.each do |column|
value = read_attribute(column)
write_attribute(column, nil) if value.blank?
end
end
end
#example AR class where you are accepting data from a form and don't want to allow empty strings for NOT NULL columns
class User < ActiveRecord::Base
include NilifyBlanks
before_save do |record|
record.nilify_blanks(
:login,
:email,
:first_name,
:last_name,
:phone
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment