0

I am working with a legacy database that has a bit of a design quirk. There is a column set to NOT NULL but that has a default value of "" (empty string). This is causing me issues when attempting to save to this column. Rails is automatically turning any attribute that is empty to nil.

my_class = MyClass.new
my_class.variable = ''

this will evaluate to nil, I understand the Rails convention is to send nil, it makes sense, but in this case I have to send the empty string for data integrity. How can I force ActiveRecord to actually save the empty string to the database?

Edit:

# Console
1.9.3-p484 :002 > my_class = TestClass.new
=> nil
1.9.3-p484 :003 > my_class.name = 'hello'
=> "hello"
1.9.3-p484 :004 > my_class.name
=> "hello"
1.9.3-p484 :005 > my_class.name = ''
=> ""
1.9.3-p484 :006 > my_class.name
=> nil

The attribute's getter will always return nil even when I set it as an empty string.

3
  • 1
    AFAIK there's no rails convention to save "" as null, in string or text format fields at least. Commented Feb 4, 2014 at 14:19
  • I'm getting string for last line. not nil.... Commented Feb 4, 2014 at 14:45
  • That is what I would expect but this is maddening. I'm using rails 3.2.13 and every attribute on the model behaves this way. I have a Rails 4 project that does not do this. Commented Feb 4, 2014 at 14:54

2 Answers 2

2

What is the datatype of the column? If it's string then it should let you save the empty string. if it's (eg) integer it will save "" as "null".

Sign up to request clarification or add additional context in comments.

1 Comment

It is a string. Oddly, if I set the variable to '' and then in query the variable, it just tells me it's nil. Even in the console I can see it happen.
0

Use before_save callback to replace nil into ''.

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.