3

I'm using ActiveAdmin and if I edit an entry and leave a TEXT field blank, in the db it gets set as empty string -- when it really should be getting set as NULL (and NULL is allowed on the schema for those fields).

Has anyone else encountered this issue and solved it?

1
  • 1
    I would consider this a feature, not an issue. NULL fields in the database should be avoided if possible. They generally just mess up data integrity and can create a whole bunch of problems for you as a developer. Is there an actual reason you want (or need) NULL values in your database? You can read about some of the problems NULL values can cause here: databasedesign-resource.com/null-values-in-a-database.html Commented Dec 18, 2011 at 13:02

1 Answer 1

5

(Moved from comments, as I found more and more to say about it):

I haven't used ActiveAdmin, but... Any reason why an empty string wouldn't be stored as an empty string but a NULL?

I think the empty-string-to-Nil conversion should never be automatic, since it violates least surprise. I'd appreciate a doc reference stating the opposite if I'm wrong...

As for solving it, I'd guess this might do the trick:

before_validation do
  self.mytextfield = nil if self.mytextfield && self.mytextfield.empty?
end

Or, more systemic, this gem.

class MyModel < ActiveRecord::Base
  nilify_blanks :only => [:mytextfield]
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.