Why does ActiveRecord store empty strings?
This week I have been reading Programming Ecto as I continue to explore my interest in elixir. As I was reading through the book, this line jumped out at me:
By default, the cast function will treat the empty string "" as nil when creating the changeset.
As a Rails developer for the last 6 or 7 years, I have to admit I had a bit of an epiphany that was followed by envy.
When a form field for an optional column in Rails is left blank, ActiveRecord
will store these in Postgres as ""
instead of null
when it's submitted to the database. This can lead to an odd-state similar to the three-state boolean. Essentially, it forces you to write code like the following that checks for multiple value types that represent an empty state:
class User < ApplicationRecord
scope :emailable, -> { where.not(email: [nil, ""]) }
end
A gem to the rescue
The best answer I've found to always storing them as null
is the nilify_blanks gem. I haven't introduced this gem into an app yet, but I do think this is the behavior that I want. I just don't know how I feel about introducing a dependency and changing Rails default behavior.
The more time I spend in this career, the more hesitant I am to introduce dependencies or stray away from the mainstream. I'd rather see this behavior get introduced into ActiveRecord
. But as I say that...
There's a good chance that I'm missing something
I don't know if there is any value in storing these empty strings vs storing nulls, but I'm humble enought to know that I could be missing something here. Do you think there's an advantage to ActiveRecord
's approach vs Ecto
's? I'd love to hear what you think, @michaelanhari.