Carsten
Carsten

Reputation: 593

Nested form in active_admin with select or create option

We are using active_admin for our administration backend.

We have a model "App" that :belongs_to model "Publisher":

class App < ActiveRecord::Base
  belongs_to :publisher
end

class Publisher < ActiveRecord::Base
  has_many :apps
end

When creating a new entry for the "App" model I want to have the option to either select an existing publisher or (if the publisher is not yet created) to create a new publisher in the same (nested) form (or at least without leaving the page).

Is there a way to do this in active_admin?

Here's what we have so far (in admin/app.rb):

form :html => { :enctype => "multipart/form-data" } do |f|
  f.inputs do
    f.input :title
    ...
  end

  f.inputs do
    f.semantic_fields_for :publisher do |p| # this is for has_many assocs, right?
      p.input :name
    end
  end

  f.buttons
end

After hours of searching, I'd appreciate any hint... Thanks!

Upvotes: 19

Views: 6604

Answers (4)

Naysawn
Naysawn

Reputation: 221

I've found you need to do 3 things.

Add semantic fields for the form

f.semantic_fields_for :publisher do |j|
  j.input :name
end

Add a nested_belongs_to statement to the controller

controller do
    nested_belongs_to :publisher, optional: true
end

Update your permitted parameters on the controller to accept the parameters, using the keyword attributes

permit_params publisher_attributes:[:id, :name]

Upvotes: 0

datnt
datnt

Reputation: 374

According to ActiveAdmin: http://activeadmin.info/docs/5-forms.html

You just need to do as below:

f.input :publisher

Upvotes: 5

Cristian
Cristian

Reputation: 6077

First, make sure that in your Publisher model you have the right permissions for the associated object:

class App < ActiveRecord::Base
  attr_accessible :publisher_attributes

  belongs_to :publisher
  accepts_nested_attributes_for :publisher, reject_if: :all_blank
end

Then in your ActiveAdmin file:

form do |f|
  f.inputs do
    f.input :title
    # ...
  end

  f.inputs do
    # Output the collection to select from the existing publishers
    f.input :publisher # It's that simple :)

    # Then the form to create a new one
    f.object.publisher.build # Needed to create the new instance
    f.semantic_fields_for :publisher do |p|
      p.input :name
    end
  end

  f.buttons
end

I'm using a slightly different setup in my app (a has_and_belongs_to_many relationship instead), but I managed to get it working for me. Let me know if this code outputs any errors.

Upvotes: 9

bruno
bruno

Reputation: 93

The form_builder class supports a method called has_many.

f.inputs do
  f.has_many :publisher do |p|
    p.input :name
  end
end

That should do the job.

Update: I re-read your question and this only allows to add a new publisher, I am not sure how to have a select or create though.

Upvotes: 7

Related Questions