Skip to content

Commit

Permalink
Fallback to String field with warning instead of raising error when a…
Browse files Browse the repository at this point in the history
… matching field can't be found
  • Loading branch information
excid3 committed Nov 4, 2024
1 parent bb557c0 commit c7281f3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 18 deletions.
29 changes: 11 additions & 18 deletions lib/madmin/resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,16 @@ def attribute(name, type = nil, **options)
type ||= infer_type(name)
field = options.delete(:field) || field_for_type(type)

if field.nil?
Rails.logger.warn <<~MESSAGE
WARNING: Madmin could not infer a field type for `#{name}` attribute. Defaulting to a String type.
You can set the type by specifying the type on the attribute:
attribute :#{name}, :boolean
MESSAGE
field = Fields::String
end

config = ActiveSupport::OrderedOptions.new.merge(options)
yield config if block_given?

Expand All @@ -61,23 +71,6 @@ def attribute(name, type = nil, **options)
type: type,
field: field.new(attribute_name: name, model: model, resource: self, options: config)
)
rescue KeyError
raise ArgumentError, <<~MESSAGE
Madmin couldn't find a field type called `:#{type}`
MESSAGE
rescue => e
builder = ResourceBuilder.new(model)
raise ArgumentError, <<~MESSAGE
Madmin couldn't find attribute or association '#{name}' on #{model} model.
We searched these attributes and associations:
#{(builder.attributes + builder.associations).join(", ")}
This attribute is defined in a Madmin resource at:
#{e.backtrace.find { |l| l =~ /_resource.rb/ }}
Either add the missing attribute or assocation, or remove this line from your Madmin resource.
MESSAGE
end

def friendly_name
Expand Down Expand Up @@ -204,7 +197,7 @@ def field_for_type(type)
has_one: Fields::HasOne,
rich_text: Fields::RichText,
nested_has_many: Fields::NestedHasMany
}.fetch(type)
}[type]
end

def infer_type(name)
Expand Down
2 changes: 2 additions & 0 deletions test/dummy/app/madmin/resources/user_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ class UserResource < Madmin::Resource
attribute :avatar, index: false
attribute :something, :string, index: false, form: false

attribute :missing

# Associations
attribute :posts, :nested_has_many, skip: %I[attachments]
attribute :comments
Expand Down

0 comments on commit c7281f3

Please sign in to comment.