Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

AR: Store empty strings as NULL, making queries + conditions simpler and code more robust

branch: master

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 lib
Octocat-spinner-32 spec
Octocat-spinner-32 tasks
Octocat-spinner-32 .gitignore
Octocat-spinner-32 README.markdown
Octocat-spinner-32 Rakefile
Octocat-spinner-32 VERSION
Octocat-spinner-32 clear_empty_attributes.gemspec
Octocat-spinner-32 init.rb
README.markdown

Problem

When AR objects are saved, empty fields are saved as '' instead of nil.

  • Complicates queries for empty fields (WHERE field IS NULL OR field = '')
  • Makes the use of unless field.blank? necessary (opposed to only if field)
  • Can lead to late-detected bugs because most of the time strings were filled or '' and suddenly they are nil
  • Some validations do not support :allow_blank=>true
  • Databases can handle NULL better & faster than empty strings (especially when using LIKE)

Solution

Defines an AR before_validation that sets empty Strings to nil.

Install

script/plugin install git://github.com/collectiveidea/clear_empty_attributes.git OR
sudo gem install clear_empty_attributes

Migration

When you are switching to clear_empty_attributes, run this task to remove any '' strings/texts from your database.

rake db:clear_empty_attributes

(only works when checked out or installed as plugin)

Authors

Hereby placed under public domain, do what you want, just do not hold anybody accountable...

Something went wrong with that request. Please try again.