Skip to content

Instantly share code, notes, and snippets.

@Haumer
Created January 21, 2021 09:37
Show Gist options
  • Save Haumer/07dfe9169ec58bef4e10b474dea788fd to your computer and use it in GitHub Desktop.
Save Haumer/07dfe9169ec58bef4e10b474dea788fd to your computer and use it in GitHub Desktop.

simple_form_array_input.rb

class ArrayInput < SimpleForm::Inputs::StringInput
  def input
    input_html_options[:type] ||= input_type

    existing_values = Array(object.public_send(attribute_name)).map do |element|
      @builder.text_field(nil, input_html_options.merge(value: element, name: "#{object_name}[#{attribute_name}][]"))
    end

    existing_values.push @builder.text_field(nil, input_html_options.merge(value: nil, name: "#{object_name}[#{attribute_name}][]"))
    existing_values.join.html_safe
  end

  def input_type
    :string
  end
end

View

<%= f.input :elements, as: :array, input_html: { class: "form-control" } %>

Model

def remove_blank_elements
  elements.reject!(&:blank?)
end
def strong_params
  params.require(:model).permit(elements: [])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment