Last active
September 19, 2018 09:19
-
-
Save gpichot/83fbb0e60305db8cd699cf4e2448c91f to your computer and use it in GitHub Desktop.
Simple Form input to generate multiple selects
This file contains hidden or 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
# frozen_string_literal: true | |
# To use with a ActiveRecord array column for instance: | |
# add_column :myobjects, :features, :integer, array: true, default: [] | |
# | |
# Based on https://tenforward.consulting/blog/integrating-an-array-column-in-rails-with-simple-form | |
class ArraySelectInput < SimpleForm::Inputs::CollectionSelectInput | |
def input(wrapper_options = nil) | |
label_method, value_method = detect_collection_methods | |
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options) | |
name = "#{object_name}[#{attribute_name}][]" | |
select_options = merged_input_options.merge(name: name) | |
existing_values = Array(object.public_send(attribute_name)).map do |item| | |
build_select_item(item, select_options, label_method, value_method) | |
end | |
existing_values.push build_select_item(nil, select_options, label_method, value_method) | |
existing_values.join.html_safe | |
end | |
def build_select_item(value, select_options, label_method, value_method) | |
input_options_with_value = input_options.merge(selected: value) | |
@builder.collection_select( | |
attribute_name, collection, value_method, label_method, | |
input_options_with_value, select_options | |
) | |
end | |
end |
This file contains hidden or 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 MyController < ApplicationController | |
def my_params | |
p = params.require(:myobject).permit( | |
features: [] | |
) | |
# You may want to remove empte values, and to keep only unique values | |
p[:features] = p[:features].reject(&:empty?) #.uniq | |
p | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment