Last active
February 6, 2019 02:55
-
-
Save ksouthworth/3ab62053d6873b32679f1c6e6019f1e6 to your computer and use it in GitHub Desktop.
SimpleForm Sticky Association Input
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
-# form.html.haml | |
= simple_form_for @project do |f| | |
-# normal SimpleForm association | |
= f.association :company | |
-# new and improved "sticky" association | |
= f.sticky_association :company | |
= f.input :name | |
= f.submit |
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
# config/initializers/simple_form_sticky_association.rb | |
require 'simple_form' | |
SimpleForm::FormBuilder.class_eval do | |
def sticky_association(association, options = {}, &block) | |
# adapted from https://github.com/plataformatec/simple_form/blob/master/lib/simple_form/form_builder.rb#L206 | |
options = options.dup | |
return simple_fields_for(*[association, options.delete(:collection), options].compact, &block) if block_given? | |
raise ArgumentError, "Association cannot be used in forms not associated with an object" unless @object | |
reflection = find_association_reflection(association) | |
raise "Association #{association.inspect} not found" unless reflection | |
options[:as] ||= :select | |
options[:collection] ||= fetch_association_collection(reflection, options) | |
# Custom logic | |
# Ensure the associated model is included in the collection | |
associated_id = self.object.send(reflection.foreign_key) | |
collection_items = options[:collection].to_a | |
item_exists = collection_items.find_index{|x| x.id == associated_id}.present? | |
if (!item_exists) | |
associated_model = reflection.klass.unscoped.find(associated_id) | |
collection_items.push(associated_model) | |
options[:collection] = collection_items | |
end | |
# End custom logic | |
attribute = build_association_attribute(reflection, association, options) | |
input(attribute, options.merge(reflection: reflection)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment