simple_form icon indicating copy to clipboard operation
simple_form copied to clipboard

Make field type detection ActiveModel compliant

Open theycallmeswift opened this issue 6 years ago • 1 comments

Hey, folks!

I'm using Simple Form with some basic form objects that rely on the ActiveModel attributes API. Unlike ActiveRecord, ActiveModel classes do not benefit from automatic type detection because they don't implement type_for_attribute or has_attribute?.

To achieve this behavior I've been adding the following to my models:

class Events
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :registration_open, :boolean, default: false

  def has_attribute?(attr_name)
    @attributes.keys.include?(attr_name.to_s)
  end

  def type_for_attribute(attr_name, &block)
    attr_name = attr_name.to_s
    if block
      self.class.attribute_types.fetch(attr_name, &block)
    else
      self.class.attribute_types[attr_name]
    end
  end
end

Would there be interest updating the find_attribute_column method to directly access attribute_types instead of going through type_for_attribute?

Relevant code:

https://github.com/plataformatec/simple_form/blob/aae6f9b6fd3983abc14eaddd410662c6c828ec10/lib/simple_form/form_builder.rb#L580-L586

theycallmeswift avatar Jul 08 '19 19:07 theycallmeswift

@theycallmeswift Hmmm, type_for_attribute would be nice for ActiveModel generally. Have you considered a Rails PR to move type_for_attribute from ActiveRecord up to ActiveModel? I'm not sure if it would be accepted, but other ActiveModel parts have followed that path, and the code seems to only use things already available in ActiveModel.

ansonhoyt avatar Sep 22 '23 15:09 ansonhoyt