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:
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)