Last active
February 22, 2019 14:30
-
-
Save jabbett/75546a140bc133616f623686278ea6f8 to your computer and use it in GitHub Desktop.
ActsAsTaggableOn with collection_check_boxes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= 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 %> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Sundae < ApplicationRecord | |
FLAVORS = ['Chocolate', 'Vanilla', 'Strawberry', 'Grapenut'] | |
acts_as_taggable_on :flavors | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SundaesController < ApplicationController | |
# ... | |
private | |
def sundae_params | |
params.require(:sundae).permit(:flavor_list => []) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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