Search code examples
ruby-on-railscheckboxenumssimple-formruby-on-rails-5

How do I properly store multiple checkboxed values using SimpleForm?


Basically I want to create an option in my form that accepts checkboxes (0 to all values accepted).

I love the structure of enums, because I get the performance speed of storing the integer in the DB, but I can reference the symbol in my code. However, I doubt I can use enum when I am storing multiple values like a checkbox.

So the way I imagine it working best is to just store it as a string that is also an array. So something like this:

#  refactor_rule           :string           default([]), is an Array

Then my form looks like this:

<%= f.input :refactor_rule, collection: ["dry", "concise", "performant"], as: :check_boxes, class: "form-control" %>

The issue with this approach is when I store just 1 or 2 of the options (i.e. not all), this is what the attribute looks like:

q.refactor_rule
=> ["", "dry", "concise"]

Which I hate, because of the empty value at [0].

So my questions are as follows:

  1. What's the most performant way to achieve this? Note that the options in my checkbox are static, but the field needs to accept multiple not 1?
  2. How do I only store the values checked and not empty values?
  3. Is there any way to take advantage of Rails built-in enum functionality even though I am storing multiple values?

Solution

  • You can always have something like this to "clean" your attributes :

    q.refactor_rule.reject!(&:empty?)
    

    Which is gonna reject all empty elements from you array. Mind the !. reject! replaces it without the empty elements, reject just returns it. Your call !

    If you really need to store an array in database, you can do it like so, in your migration :

    create_table :products do |t|
       t.text :tags, array: true, default: []
    end
    

    (This is from this blog post from Plataformatec)