Skip to content

Commit

Permalink
Handle STI models where the resource is generated for the superclass
Browse files Browse the repository at this point in the history
  • Loading branch information
excid3 committed Aug 14, 2024
1 parent d4a5276 commit c4345a6
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 7 deletions.
3 changes: 2 additions & 1 deletion app/views/madmin/fields/belongs_to/_index.html.erb
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<% if (object = field.value(record)) %>
<%= link_to Madmin.resource_for(object).display_name(object), Madmin.resource_for(object).show_path(object) %>
<% object_resource = Madmin.resource_for(object) %>
<%= link_to object_resource.display_name(object), object_resource.show_path(object) %>
<% end %>
11 changes: 10 additions & 1 deletion lib/madmin.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,16 @@ def resource_for(object)
if object.is_a? ::ActiveStorage::Attached
"ActiveStorage::AttachmentResource".constantize
else
"#{object.class.name}Resource".constantize
begin
"#{object.class.name}Resource".constantize
rescue
# For STI models, see if there's a superclass resource available
if object.class.inheritance_column.present?
"#{object.class.superclass.name}Resource".constantize
else
raise
end
end
end
end

Expand Down
19 changes: 14 additions & 5 deletions lib/madmin/resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,17 @@ def inherited(base)
super
end

def model
@model ||= model_name.constantize
def model(value=nil)
if value
@model = value
else
@model ||= model_name.constantize
end
end

def model_find(id)
friendly_model? ? model.friendly.find(id) : model.find(id)
record = friendly_model? ? model.friendly.find(id) : model.find(id)
becomes(record)
end

def model_name
Expand Down Expand Up @@ -95,11 +100,15 @@ def new_path
end

def show_path(record)
url_helpers.polymorphic_path([:madmin, route_namespace, record])
url_helpers.polymorphic_path([:madmin, route_namespace, becomes(record)])
end

def edit_path(record)
url_helpers.polymorphic_path([:madmin, route_namespace, record], action: :edit)
url_helpers.polymorphic_path([:madmin, route_namespace, becomes(record)], action: :edit)
end

def becomes(record)
record.class == model ? record : record.becomes(model)
end

def param_key
Expand Down

0 comments on commit c4345a6

Please sign in to comment.