Created
March 20, 2014 07:10
-
-
Save dougcole/9658739 to your computer and use it in GitHub Desktop.
Handle empty strings with ActiveRecord
This file contains hidden or 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
module NilifyBlanks | |
def nilify_blanks(*columns) | |
columns.each do |column| | |
value = read_attribute(column) | |
write_attribute(column, nil) if value.blank? | |
end | |
end | |
end |
This file contains hidden or 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
#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