Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested has_many resource form with Active Admin doesn't do an update

I can't figure out how to use the nested resources input helpers in Active Admin to allow me to update the values of the associated records, for the "parent" record.

The model I'm trying to generate an update for is like this:

class Page < ActiveRecord::Base
  has_many :page_attributes
  accepts_nested_attributes_for :page_attributes, allow_destroy: true
end

where PageAttribute has two attributes, :key and :value

And the ActiveAdmin model is:

ActiveAdmin.register Page do
  permit_params page_attributes_attributes: [:key, :value, :_destroy => true]

  form do |f|
    f.inputs do
      f.has_many :page_attributes, allow_destroy: true, heading: 'Parts' do |page_part|
    page_part.input :key
    page_part.input :value
      end
    end

    f.actions
  end
end

But when I call up http://localhost:3000/admin/pages/2/edit, and change the value of an existing attribute (or when I check the Delete checkbox,) what happens instead is that a new record for the PageAttribute model is created and the existing associations are left untouched.

I read through the Active Admin documentation on nested resources, and a bunch of SO posts but can't figure out what I'm doing wrong :(

like image 408
sameers Avatar asked Apr 03 '14 05:04

sameers


1 Answers

I realized what I did wrong - I sort of over-thought it a bit. I didn't know that when you permit strong parameters, you have to also permit the :id parameter on an associated record you're trying to update. I sort of assumed Rails magic would take care of that.

So it works if you change the permit_params call to say this instead:

permit_params page_attributes_attributes: [:id, :key, :value, :_destroy => true]

In fact, that's what the Strong Parameters section on the Active Admin Github wiki says to do, I should have paid attention to why it was set up that way.

like image 169
sameers Avatar answered Oct 11 '22 14:10

sameers