module ExpressTemplates::Components::Forms::OptionSupport

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.

Public Instance Methods

belongs_to_association() click to toggle source

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.

# 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_association() click to toggle source
# 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

Protected Instance Methods

cols() click to toggle source
# File lib/express_templates/components/forms/option_support.rb, line 48
def cols
  @cols ||= (belongs_to_association||has_many_through_association).klass.columns
end
option_name_method() click to toggle source
# File lib/express_templates/components/forms/option_support.rb, line 52
def option_name_method
  @option_name_method ||=
    if cols.detect {|column| column.name.eql?('name') } ||
       resource_class.instance_methods.include?(:name)
      :name
    else
      if string_col = cols.detect {|column| column.type.eql?(:string) }
        string_col.name.to_sym
      else
        :id
      end
    end
end
option_value_method() click to toggle source
# File lib/express_templates/components/forms/option_support.rb, line 44
def option_value_method
  :id
end