Gareth Burrows
Gareth Burrows

Reputation: 1182

rails set selection value to null rather than blank

I have the following code which allows a user to select a currency rather than inheriting one.

%dd= user_field(@user, :remuneration_currency, :type => :select, :collection => REMUNERATION_CURRENCIES)

I need to allow people to set this field back to NULL, which means that the user will pick up their account's default currency. However, if I change the code to this...

%dd= user_field(@user, :remuneration_currency, :type => :select, :collection => REMUNERATION_CURRENCIES, :blank => 'Company Default')

then it sets the value to blank (as it says on the tin) rather than NULL in the database. How do I set the 'Company Default' value to be NULL rather than blank.

Upvotes: 2

Views: 771

Answers (1)

Liyali
Liyali

Reputation: 5693

Your best option is to use the gem nilify_blanks which does exactly what you are looking for:

In Rails when saving a model from a form and values are not provided by the user, an empty string is recorded to the database instead of a NULL as many would prefer (mixing blanks and NULLs can become confusing). This plugin allows you to specify a list of attributes (or exceptions from all the attributes) that will be converted to nil if they are blank before a model is saved.

Upvotes: 1

Related Questions