I noticed when submitting empty fields that my models were failing validation. It appears that a blank value in the edit view leads to an empty string being submitted to the model. Should we nil these out?
Update: submitting a blank value for an integer field results in a 0 when it should be nil.
Good catch. It makes sense to me to nil those values out. If you want to take a crack at that, go ahead. Otherwise it's going to sit a bit - I'm a bit backed up with issues at the moment.
Ah, this is causing trouble for me to. I'm going to see if I can solve it.
Any update on this?
I've also run into this issue recently and am curious if there are any updates.
Finally getting around to looking at this again. My use case is actually for a string field that needs to save null to the database if the submitted value is an empty string. I would be happy to do a PR that only takes care of number fields, but should the new behavior be configurable or should blank input values always be converted to nil?
I think empty strings should be converted to nil by default. Can't really think of a use case for why you'd want empty strings, but could be configurable in the field settings, something like:
Field::String.with_options(allow_empty_strings: true)
There are probably cases where a database has a string field where null is not allowed but empty strings are an acceptable value. If we change the current behavior of administrate it could break people's admin until they make schema changes or patch their admin dashboards.
Good point. Maybe allowing nil should be opt-in instead for now? Still seems like allowing empty strings is more of the edge case, but I understand it's a breaking change.
We are pre-1.0, so I'm currently happy with making a breaking change (we'll make a point of communicating this the best we can), so I'd not rule that out.
Adding an option first though might be a nice idea (which we can later flip) as then people can get the fix sooner.
@geoffharcourt did you manage to find a solution for this? I'm having this problem right now. :|
I also run into the same problem, is there now an option as mentioned by @nickcharlton ?
@nickcharlton Any update on this?
@geoffharcourt Should we open this issue?
@geoffharcourt @nickcharlton Was there an update or solution to this?
This is my workaround:
# app/controllers/admin/application_controller.rb
module Admin
class ApplicationController < Administrate::ApplicationController
...
# Hack: Store nil instead of empty String values when submitting forms
# https://github.com/thoughtbot/administrate/issues/441
def read_param_value(data)
new_data = if data.is_a?(String) and data.blank?
nil
elsif data.is_a?(ActionController::Parameters)
data.transform_values{ |v| read_param_value(v) }
else
data
end
super(new_data)
end
end
end
Most helpful comment
This is my workaround: