Skip to content

JSON editor is not present when creating nested resources #7

@sedubois

Description

@sedubois

I have a Post which has_many Post::Translations, which themselves have a JSON tags property. When creating the post with its nested resource(s), the tag editor does not appear (http://localhost:3000/admin/posts/new):

Screenshot 2019-10-28 at 21 38 41

However it does appear when creating the translation sub-resource directly (http://localhost:3000/admin/post/translations/new):

Screenshot 2019-10-28 at 21 42 44

Also, the editor does appear when editing an existing post:

Screenshot 2019-10-28 at 21 57 15

The dashboard is configured as follows:

# app/dashboards/post_dashboard.rb
class PostDashboard < Administrate::BaseDashboard
  ATTRIBUTE_TYPES = {
    translations: NestedHasMany.with_options(class_name: "Post::Translation"),
    ...
  }.freeze
  FORM_ATTRIBUTES = %i[
  translations
  ...
  ].freeze
end

# app/dashboards/post/translation_dashboard.rb
class Post::TranslationDashboard < Administrate::BaseDashboard
  ATTRIBUTE_TYPES = {
    ...
    tags: Field::JSONB,
    ...
  }.freeze
end

# app/fields/nested_has_many.rb
require "administrate/field/base"

class NestedHasMany < Administrate::Field::NestedHasMany
  def self.permitted_attribute(associated_resource, _options = nil)
    {
      "#{associated_resource}_attributes".to_sym =>
        associated_attributes(associated_resource, _options),
    }
  end

  def self.associated_attributes(associated_resource, _options)
    dashboard_class = dashboard_for_resource(associated_resource, _options)
    DEFAULT_ATTRIBUTES + dashboard_class.new.permitted_attributes
  end

  # Hack: reimplement Administrate::Field::NestedHasMany.dashboard_for_resource to preserve namespace
  def self.dashboard_for_resource(resource, _options)
    class_name = _options && _options[:class_name] || resource.to_s.classify
    "#{class_name}Dashboard".constantize
  end

  def association_name
    options.fetch(
      :association_name,
      associated_class_name.underscore.pluralize[/([^\/]*)$/, 1],
    )
  end
end

As my tags cannot be nil (as enforced by DB schema), this issue prevents creating new posts and is therefore quite blocking.

Using Rails 5.2.3, Administrate 0.12.0, administrate-field-jsonb 0.4.0, and administrate-field-nested_has_many 1.1.0 although it's mostly overridden; code is included for reference above but in principle unrelated to this issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions