nickcharlton / administrate-field-nested_has_many

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

How to determine missing accepts_nested_attributes_for when encourntering new_record?/nil error #58

Open SumOys opened 2 years ago

SumOys commented 2 years ago

I was running into the new_record?/nil class issue described in the readme.

undefined method `new_record?' for nil:NilClass

        is_dynamic = f.object.new_record?
                             ^^^^^^^^^^^^

I have my models listed in a namespace, and had to apply this fix to get them to work with Administrate. For nested_has_many, the Administrate fix wasn't enough and I had to also add the class_name to the field options:

  ATTRIBUTE_TYPES = {
    country_tax_note: Field::NestedHasMany.with_options(class_name: "ColaCom::CountryTaxNote", skip: :tax_country),
    tax_state: Field::HasMany,
...
...

I tried adding the appropriate accepts_nested_attributes_for lines in my ColaCom::TaxCountry model

    has_many :country_tax_note, dependent: :destroy
    has_many :tax_state, dependent: :destroy

    accepts_nested_attributes_for :country_tax_note, reject_if: :all_blank, allow_destroy: true
    accepts_nested_attributes_for :tax_state, reject_if: :all_blank, allow_destroy: true 
    ...
    ...

but I still get this error. Is there any way to debug exactly which nested attribute I'm missing?

pablobm commented 2 years ago

Not sure what you are asking. Do you mean which of the two of :country_tax_note and :tax_state is failing? If that's what you mean, perhaps you could use the gem web-console to get a debugging console in the error message page.

With the gem in your Gemfile, start the dev server and trigger the error. Then, on the backtrace list, click on the entry that may look interesting (I just tried forcing the error and for me it was .../app/views/fields/nested_has_many/_fields.html.erb:8). Now you can use the web console to see the variable values at that point. For me I could enter field and it told me which field had the problem:

>> field
=> #<Administrate::Field::NestedHasMany:0x00007fb63405fb30 @attribute=:students, @data=#<ActiveRecord::Associations::CollectionProxy []>, @page=:form, @resource=#<School id: nil, name: nil, created_at: nil, updated_at: nil>, @options={}, @new_resource=#<Foo::Student id: nil, name: nil, school_id: nil, created_at: nil, updated_at: nil>>

Does that help at all? Is it something else that you are looking for?