heartcombo / simple_form

Forms made easy for Rails! It's tied to a simple DSL, with no opinion on markup.
http://blog.plataformatec.com.br/tag/simple_form
MIT License
8.21k stars 1.31k forks source link

Make field type detection ActiveModel compliant #1666

Closed theycallmeswift closed 2 months ago

theycallmeswift commented 5 years ago

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

ansonhoyt commented 12 months ago

@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.

nashby commented 2 months ago

@theycallmeswift hey! Looks like Rails finally moved it to ActiveModel and it's going to be part of Rails 7.2 release https://github.com/rails/rails/pull/49910 so I'm closing this. Thanks for looking into it anyway!