Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord + ActiveAdmin, save a empty string instead of null

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'
like image 535
Cornelius Avatar asked May 03 '17 16:05

Cornelius


2 Answers

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

like image 98
Md. Farhan Memon Avatar answered Sep 21 '22 10:09

Md. Farhan Memon


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
like image 43
Piers C Avatar answered Sep 23 '22 10:09

Piers C