Soroush Hakami
Soroush Hakami

Reputation: 5396

drop down list option value to null

I have a drop down list with multiple radio button values to choose from. If you don' t choose a option the value will be saved in the database as null. But if you choose an option, you can't uncheck it. So I need a "not stated" option in the dropdown list instead, which would save the value as null in the database.

How can I in the best possible way change these settings so that I can save the value null in the database. I need to alter this code below so an extra option "not selected" value appears and when "not selected" is chosen the value null will be saved to the database

<%= account_pref.input "editorial_#{key}".to_sym, :as => :radio, :collection => options_for(Editorial, key.to_sym), :wrapper_html => { :class => "compact" }, :label => key.titleize  %>

Upvotes: 2

Views: 1692

Answers (1)

dslh
dslh

Reputation: 1835

Just the empty string should do it I think.

:collection => [['<none>','']] + options_for(Editorial, key.to_sym)

That worked for me with an integer field, for a string field it might be harder because option values can only be strings and there's not really a concept of null values in forms. Maybe someone knows a clever trick here but you could always sort it out in the controller:

def create
  @account = Account.new(params[:account])
  @account.editorial = nil if @account.editorial.empty?

  ...
end

Or maybe override the setter in your model to do the same thing. Either option feels a bit hack-ish, though.

Upvotes: 1

Related Questions