nickcharlton / administrate-field-nested_has_many

A plugin for nested has_many forms in Administrate
MIT License
59 stars 99 forks source link

JS enhancements not active on new sub-records #49

Open pablobm opened 3 years ago

pablobm commented 3 years ago

When a NestedHasMany field in turn contains an associative field, such as a BelongsTo, the JS enhancements from Administrate do not apply correctly when adding new sub-records.

This is an example model:

class Recipe < ApplicationRecord
  has_many :recipe_ingredients
  has_many :ingredients, through: :recipe_ingredients

  accepts_nested_attributes_for(
    :recipe_ingredients,
    reject_if: :all_blank,
    allow_destroy: true
  )
end

And the corresponding dashboard:

require "administrate/base_dashboard"

class RecipeDashboard < Administrate::BaseDashboard
  ATTRIBUTE_TYPES = {
    id: Field::Number,
    name: Field::String,
    recipe_ingredients: Field::NestedHasMany.with_options(
      skip: [:recipe]
    ),
  }.freeze

  # ...
end

When creating or editing a recipe, if I click to "Add Recipe Ingredient", the new sub-form for RecipeIngredient will have a plain select dropdown. However pre-existing records of RecipeIngredient will be enhanced with Selectize (as provided by Administrate by default):

Two sub-forms in a NestedHasMany field: the first is enhanced with Selectize, while the second isn't

dadachi commented 2 years ago

Add this code:

<%# app/views/admin/application/_javascript.html.erb %>

<%= javascript_tag do %>
  $('.field-unit--nested').on('cocoon:after-insert', function() {
    $('.field-unit--belongs-to select').selectize({});
  });
<% end %>
jamiecobbett commented 1 year ago

I tried following @dadachi's suggestion, but it instead removed all of the JS.

I think the step I missed was to first copy app/views/admin/application/_javascript.html.erb from the administrate source (which you can do manually, or via rails generate administrate:views:layout), and then add the code above.

I wonder if this could be done in the gem around here? https://github.com/nickcharlton/administrate-field-nested_has_many/blob/94500b6355a291f3ae604333561f1b3e0b57df10/lib/administrate/field/nested_has_many.rb#L12-L14

AimanFarhanMohdFaruk commented 1 year ago

Did anyone manage to fix this yet ?