6

When I use the Active Admin form, the empty string values are saved as "" (empty) instead of NULL value.

Is there a parameter I should set in the initializer to save every empty values as NULL in MySQL?

form do |f|
    input :label
    input :description, as: :text
    input :country
    input :city
  end
  actions
end

This is my migration schema:

create_table "projects" do |t|
  t.string "label", limit: "40"
  t.string "country", limit: "2"
  t.string "city", limit: "200"
  t.string "description", limit: 600
end

And this is my Gemfile.

gem 'rails', '~> 5.1.0.rc1'
gem 'mysql2', '>= 0.3.18', '< 0.5'
gem 'puma', '~> 3.0'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
gem 'active_model_serializers', '~> 0.10.5', require: true
gem 'kaminari'
gem 'inherited_resources', '~> 1.7'
gem 'activeadmin', '~> 1.0.0.pre5'
gem 'sidekiq', '~> 4.2.10'
gem "paperclip", "~> 5.1.0"
gem 'aws-sdk', '~> 2.3.0'
2
  • What's the issue you are facing because of this? Commented May 3, 2017 at 16:47
  • The form saves empty values as "" instead of NULL in the MySQL table. Commented May 3, 2017 at 16:55

2 Answers 2

1

That seems to be the default behaviour of forms. I came accross this gem nilify_blanks which will solve your issue. Hope it helps.

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

3 Comments

I saw the gem but the build flag has an error status. And I thought is was deprecated
I see that too, but you can try and let me know if it breaks ur code, worth a try if you want it for all models keeping it dry. And I think you might have came accross this solution too if not see stackoverflow.com/a/40387633/6548745. It is good for limited attributes.
so which one worked for you? gem or code from the SO link? @Cornelius
1

This is a Rails, not an ActiveAdmin issue.

If you can, don't use null for empty strings. Using null may be theoretically correct, but in practice I have found working with MySQL simpler and less error prone if all varchar columns are set not null, e.g.:

t.string :label, limit: 40, null: false

The nilify_blanks gem is unmaintained since Rails 4. Instead, try the following in your model:

def label=(label)
  write_attribute :label, label.present? ? label : nil
end

1 Comment

Yes well that's your opinion however from the PoV of truth maintenance, null is someting entirely different than an empty value or a default. In a lot of cases null signals that the value is not known while an empty value signals that the value is known but empty. I don't think it will be surprising that I disagree with you here.

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.