Skip to content

Instantly share code, notes, and snippets.

@tonycoco
Last active July 15, 2017 18:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tonycoco/b5ba8dbd5298a9eefe90 to your computer and use it in GitHub Desktop.
Save tonycoco/b5ba8dbd5298a9eefe90 to your computer and use it in GitHub Desktop.
Array of Hashes input for ActiveAdmin and Formtastic
$('.array-of-hashes-tables').on('click', '.array-of-hashes-table .remove', function(event) {
event.preventDefault();
$(this).closest('.array-of-hashes-table').remove();
});
$('.array_of_hashes .add').on('click', function(event) {
event.preventDefault();
var $this = $(this);
var $tables = $this.siblings('.array-of-hashes-tables');
var $cloneable = $tables.find('.cloneable').first();
var $clone = $cloneable.clone();
$tables.append($clone);
$clone.find('input').removeAttr('disabled');
$clone.removeClass('cloneable');
$clone.show();
});
class ArrayOfHashesInput
include Formtastic::Inputs::Base
include ActionView::Helpers::FormTagHelper
def to_html
array_html = []
first_object = {}
options[:with_keys].each do |key|
first_object[key] = ""
end
array_html << input_wrapping do
hash_html = []
hash_html << '<div class="array-of-hashes-tables">'
([first_object] + Array.wrap(object.send(method))).each_with_index do |hash, index|
hash_html << '<table class="array-of-hashes-table'
hash_html << ' cloneable' if index == 0
hash_html << '"'
hash_html << ' style="display: none;"' if index == 0
hash_html << '><tbody><tr>'
hash = eval(hash) unless hash.is_a?(Hash)
hash.each do |key, value|
tag = text_field_tag("site_config[#{method}][][#{key}]", value, disabled: index == 0 ? true : nil)
hash_html << "<td>#{tag}</td>"
end
hash_html << '<td><a href="#" class="button remove">Remove</a></td>'
hash_html << "</tr></tbody></table>"
end
hash_html << "</div>"
hash_html << '<a href="#" class="button add">Add</a>'
hash_html.join("").html_safe
end
array_html.join("\n").html_safe
end
end
@almaron
Copy link

almaron commented Aug 18, 2016

Could you include an example of how to use this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment