Module: ExpressTemplates::Components::Forms::OptionSupport

Included in:
Radio, Select
Defined in:
lib/express_templates/components/forms/option_support.rb

Overview

Provides a form component with knowledge of any association on the field and an means of loading the collection for supplying options to the user.

Instance Method Summary collapse

Instance Method Details

#belongs_to_associationObject

Reflect on any association and return it if the association type is :belongs_to. Returns false if the association is not :belongs_to. Returns nil if there was a problem reflecting.



19
20
21
22
23
24
25
26
27
# File 'lib/express_templates/components/forms/option_support.rb', line 19

def belongs_to_association
  if resource_class.respond_to?(:reflect_on_association)
    # assumes the belongs_to association uses <name>_id
    reflection = resource_class.reflect_on_association(field_name.gsub(/_id$/, '').to_sym)
    if reflection && reflection.macro.eql?(:belongs_to)
      return reflection
    end
  end
end

#has_many_through_associationObject



9
10
11
12
13
14
# File 'lib/express_templates/components/forms/option_support.rb', line 9

def has_many_through_association
  if resource_class.respond_to?(:reflect_on_association)
    reflection = resource_class.reflect_on_association(field_name.to_sym)
    return reflection if reflection && reflection.macro.eql?(:has_many) && reflection.options.keys.include?(:through)
  end
end

Provide ActiveRecord code to load the associated collection as options for display.



31
32
33
34
35
36
37
38
39
40
# File 'lib/express_templates/components/forms/option_support.rb', line 31

def related_collection
  reflection = belongs_to_association || has_many_through_association
  if reflection && !reflection.polymorphic?
    if cols.detect {|column| column.name.eql?('name') }
      reflection.klass.select(option_value_method.to_sym, option_name_method.to_sym).order(option_name_method.to_sym)
    else
      reflection.klass.all.sort_by(&option_name_method.to_sym)
    end
  end
end