Fallback 'display name' for optional belongs_to associations
What would you like to be able to do? Can you provide some examples?
Recently, I ran into the following use case:
In the
index
andshow
pages of a resource that has an optional belongs to association, display a customizable fallback string (i.e 'none'), when the associated record is not present.
For example, in the index
page of a Book
that optionally belongs to an Author
, display Anonymous
if there isn't an associated author.
Is there already a way to achieve this with Field::BelongsTo
without having to generate and modify the default views of the field/resource?
How could we go about implementing that?
If possible, having an option (fallback_display_name
or similar) that can be passed to Field::BelongsTo
to be displayed in the views when the association is not present.
# app/dashboards/book_dashboard.rb
ATTRIBUTE_TYPES = {
author: Field::BelongsTo.with_options(fallback_display_name: 'Anonymous'),
}
- Can you think of other approaches to the problem?
Having a custom field OptionalBelongsTo < Field::BelongsTo
that supports the mentioned behavior.
require 'administrate/field/belongs_to'
class OptionalBelongsTo < Administrate::Field::BelongsTo
def display_associated_resource
data.present? ? super : options.fetch(:fallback_display_name, "")
end
end