thoughtbot / thoughtbot/administrate

Fallback 'display name' for optional belongs_to associations

Open
#2,286 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
6k
Forks
1.1k
PR merge metrics
No merged PRs in 30d

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading Field::BelongsTo and the example app/dashboards/book_dashboard.rb configuration, then trace how display_associated_resource is used by the default views. The work is done when an optional association can show a configurable fallback such as “Anonymous” without modifying generated field or resource views.

Written by the indexing model from the issue text.

Assessment

Tech stack
rails, ruby
Domain
backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.