Imagine that you have a “has_and_belongs_to_many” association and you wish to present the check boxes as “Tags” that can be selected………
Step 1 - add some CSS
Because I’m a Tailwinds CSS #FanBoy I’m only specifying styles that cover the check/un-check changes. I’ll make the check boxes look like Tags inline within the HTML using TailwindsCSS.
Step 2 - ERB
We can now use the collection_check_boxes
Action View Form Helper and some TailwindCSS to build the interface.
The form helper outputs a CHECKBOX and a LABEL for each of item in our collection. However we HIDE the CHECKBOX and use the active LABEL to check/uncheck the value.
The CSS we defined in Step 1 uses a simple query to change the visual stying of the LABEL directly after each hidden CHECKBOX.
Why I like this solution
I like this solution because we’re using our tools to their best advantage. Rails brings a super powerful form helper, CSS manages the switching of styles - AND - there is no JavaScript.
Sure I’m using some TailwindsCSS to style the tags, but that’s just because I’m lazy, and besides once your interface is finished you’ll move the Tailwinds definitions into CSS anyway. Won’t you.