method_for_association_chain ignores defaults collection_name: for nested belongs_to (regression in 4.0.0.beta23 / #9030)
Summary
In 4.0.0.beta23, nested belongs_to resources that set a short association via InheritedResources defaults collection_name: raise NoMethodError on index/show. beta22 worked.
Introduced by #9030 (f606e2d1 — "Fix nested belongs_to scope when resource uses an as: alias").
Reproduction
Parent association name differs from the child model plural:
class Author < ApplicationRecord
has_many :pieces, class_name: "BlogPost", inverse_of: :author, dependent: :destroy
end
class BlogPost < ApplicationRecord
belongs_to :author, inverse_of: :pieces
end
ActiveAdmin.register BlogPost do
belongs_to :author, parent_class: Author
controller { defaults collection_name: :pieces }
endNested index/show calls author.blog_posts and fails:
NoMethodError: undefined method `blog_posts' for an instance of AuthorSame pattern whenever has_many uses a short name and collection_name matches that name.
Expected
defaults collection_name: :pieces still scopes through parent.pieces, as InheritedResources documents and as beta22 did via resource_collection_name.
Actual
ActiveAdmin::ResourceController::DataAccess#method_for_association_chain always returns resource_class.model_name.element.pluralize when belongs_to?, and never consults resource_collection_name:
def method_for_association_chain
return super unless active_admin_config&.belongs_to?
active_admin_config.resource_class.model_name.element.pluralize.to_sym
endSo #9030 fixes as: alias registrations (collection name from the alias, association still the model plural) but breaks the opposite case: short has_many names with an explicit collection_name.
Suggested fix
Prefer the configured collection name when the parent responds to it; keep the model-name plural as fallback for as::
def method_for_association_chain
return super unless active_admin_config&.belongs_to?
configured = resource_collection_name
derived = active_admin_config.resource_class.model_name.element.pluralize.to_sym
return configured if configured == derived
parent = association_chain.last
return configured if parent.respond_to?(configured)
return derived if parent.respond_to?(derived)
configured
endA regression example with a short has_many + defaults collection_name: next to the existing as: specs in spec/unit/belongs_to_spec.rb would lock both behaviors.
Environment
- activeadmin
4.0.0.beta23(regression vs4.0.0.beta22) - inherited_resources
~> 2.0 - Rails 8.1
Workaround
App-side to_prepare reopen of ActiveAdmin::ResourceController with the method above.
Source: activeadmin/activeadmin