Skip to content

Instantly share code, notes, and snippets.

@jabbett
Last active February 22, 2019 14:30
Show Gist options
  • Save jabbett/75546a140bc133616f623686278ea6f8 to your computer and use it in GitHub Desktop.
Save jabbett/75546a140bc133616f623686278ea6f8 to your computer and use it in GitHub Desktop.
ActsAsTaggableOn with collection_check_boxes
<%= form_for(@sundae) do |f| %>
<!--
collection_check_boxes requires 4 parameters, the last two are methods that access
the value and text from the collection, respectively. Hence the need for
SundaesHelper.valid_flavors!
-->
<%= f.collection_check_boxes(:flavor_list, valid_flavors, :first, :first) do |b| %>
<!-- FYI: I use Bootstrap 4, so I customized how the checkboxes would render -->
<div class="form-check">
<label class="form-check-label"><%= b.check_box class: 'form-check-input' %> <%= b.value %></label>
</div>
<% end %>
<%= f.submit %>
<% end %>
class Sundae < ApplicationRecord
FLAVORS = ['Chocolate', 'Vanilla', 'Strawberry', 'Grapenut']
acts_as_taggable_on :flavors
end
class SundaesController < ApplicationController
# ...
private
def sundae_params
params.require(:sundae).permit(:flavor_list => [])
end
end
module SundaesHelper
# Because collection_check_boxes expects a collection, and not a simple array,
# we need to adapt our flavor list into something it can consume
def valid_flavors
Sundae::FLAVORS.map{ |m| [ m ] }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment