Skip to content
GitLab
Projects Groups Snippets
  • /
  • Help
    • Help
    • Support
    • Community forum
    • Submit feedback
    • Contribute to GitLab
  • Sign in / Register
  • A administrate
  • Project information
    • Project information
    • Activity
    • Labels
    • Members
  • Repository
    • Repository
    • Files
    • Commits
    • Branches
    • Tags
    • Contributors
    • Graph
    • Compare
  • Issues 96
    • Issues 96
    • List
    • Boards
    • Service Desk
    • Milestones
  • Merge requests 32
    • Merge requests 32
  • CI/CD
    • CI/CD
    • Pipelines
    • Jobs
    • Schedules
  • Deployments
    • Deployments
    • Environments
    • Releases
  • Packages and registries
    • Packages and registries
    • Package Registry
    • Infrastructure Registry
  • Monitor
    • Monitor
    • Incidents
  • Analytics
    • Analytics
    • Value stream
    • CI/CD
    • Repository
  • Wiki
    • Wiki
  • Snippets
    • Snippets
  • Activity
  • Graph
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
Collapse sidebar
  • thoughtbot, inc.
  • administrate
  • Issues
  • #2286
Closed
Open
Issue created Nov 17, 2022 by Alfonso Mancilla@ammancilla

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 and show 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
Assignee
Assign to
Time tracking