From my understanding, empty form fields saving to database usually defaults to nil (which is what I wanted). But two of my optional form fields are saving as empty ("") instead of nil.
I'm not sure why this is, I've looked at: Understanding Rails validation: what does allow_blank do? and Save blank value as nil in database thinking it may be because I am using allow_blank: true
.
My group.rb
# meetup_urlname must be unique
validates :meetup_urlname, uniqueness: { case_sensitive: false, message: "this is already being used by a different group" }, allow_blank: true
# only validate if meetup_apikey or if meetup_urlname is non-empty
validate :url_name_valid?, :if => :meetup_urlname?
validate :api_key_valid?, :if => :meetup_apikey?
_Form.html.erb:
<%= bootstrap_form_for(@group, :html => { :multipart => true }, layout: :horizontal, label_col: "col-sm-3", control_col: "col-sm-9") do |f| %>
...
<h5>Import Events from Meetup</h5>
<div class="field">
<%= f.text_field :meetup_urlname, label: "Meetup Group's URL", type: "text", placeholder: "Enter your Meetup group's url to retrieve your events", prepend: 'http://www.meetup.com/' %>
</div>
<div class="field">
<%= f.text_field :meetup_apikey, label: 'Meetup API Key', placeholder: 'Enter your Meetup API key (Required for advanced meetup functionality)' %>
</div>
<%= f.hidden_field :status %>
<%= f.hidden_field :audit_status %>
<%= f.hidden_field :sref %>
<div class="col-sm-10" style="padding-right: 26px;">
<div class="actions pull-right">
<%= f.submit 'Update Group', class: "action-btn btn-rounded btn-large" %>
</div>
</div>
<% end %>
Is there a way to have the optional form fields save as nil instead of empty by default? Currently have a hack in where if the form field returned empty..it would overwrite as nil.
Any feedback or insight would help. Thanks!