Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Boolean field select set to nil is treated as false #892

Closed
bluemont opened this Issue Oct 22, 2012 · 2 comments

Comments

Projects
None yet
2 participants
@ghost

ghost commented Oct 22, 2012

I want to set a boolean field to nil to indicate "missing" data. I wonder if formtastic is not built with idea of indicating "missing" data with nil.

Here is what I am using:

boolean = { as: :select, include_blank: false, collection: {
  "?" => nil, "No" => false, "Yes" => true }} # to stay DRY

f.input :likes_cats, boolean

Even though I specifically set the collection to use the nil, upon form submission, the field gets persisted as false.

I'm using Formtastic as part of ActiveAdmin. I'm also using MongoDB via Mongoid, so I don't expect everything to work magically out of the box. But in this case, based on looking at the logs, I suspect that Formtastic might be the layer that I have to address to fix this.

Owner

justinfrench commented Oct 23, 2012

The problem with "nil" is that browsers don't post form data without a value (so there's potential confusion as to the user intent, especially with checkboxes). It sounds like you're trying to replicate something very similar to the behaviour of :include_blank => true, where the first option in the select has no label and an empty ("") value. When the form is posted, there's three possible values that can be posted:

  • true
  • false
  • ""

It's then the job of your model layer's validations to detect the blank value and declare the object invalid. I think the syntax is something like:

validates :likes_cats, :presence => true, :allow_blank => false

Using the code you have above, I think one small incremental change to try would be changing the nil to an emoty string, then inspecting the params hash in your controller, comparing it to what was submitted previously:

boolean = { as: :select, include_blank: false, collection: {
  "?" =>"", "No" => false, "Yes" => true }} # to stay DRY
@ghost

ghost commented Oct 24, 2012

@justinfrench Thanks, your commentary is spot on. I will try it. Also, I found this which may of use to others using Mongoid:

boolean with nil values and form submission with blank strings
https://groups.google.com/forum/?fromgroups=#!topic/mongoid/78dPs0_GnWU

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment