agente_secreto
agente_secreto

Reputation: 8079

ActiveAdmin forms with has_many - belongs_to relationships?

I have the models Home and Photo, which have a has_many - belongs_to relationship (a polymorphic relationship, but I dont think that matters in this case). I am now setting up active admin and I would like admins to be able to add photos to homes from the homes form.

The photos are managed by the CarrierWave gem, which I dont know if will make the problem easier or harder.

How can I include form fields for a different model in the Active Admin Home form? Any experience doing something like this?

class Home < ActiveRecord::Base
  validates :name, :presence => true,
                     :length => { :maximum => 100 }
  validates :description, :presence => true      
  has_many :photos, :as => :photographable

end


class Photo < ActiveRecord::Base
    belongs_to :photographable, :polymorphic => true
    mount_uploader :image, ImageUploader
end

Upvotes: 21

Views: 29314

Answers (4)

MegaCasper
MegaCasper

Reputation: 1956

You could try this:

form do |f|
  f.semantic_errors # shows errors on :base
  f.inputs          # builds an input field for every attribute

  f.inputs 'Photos' do
    f.has_many :photos, new_record: false do |p|
      p.input :field_name
      # or maybe even
      p.input :id, label: 'Photo Name', as: :select, collection: Photo.all
    end
  end

  f.actions         # adds the 'Submit' and 'Cancel' buttons  
end

Also, you can look at https://github.com/activeadmin/activeadmin/blob/master/docs/5-forms.md (See Nested Resources)

Upvotes: 2

jfedick
jfedick

Reputation: 1362

Try something like this in app/admin/home.rb:

form do |f|
  f.inputs "Details" do
    f.name
  end

  f.has_many :photos do |photo|
    photo.inputs "Photos" do
      photo.input :field_name 
      #repeat as necessary for all fields
    end
  end
end

Make sure to have this in your home model:

accepts_nested_attributes_for :photos

I modified this from another stack overflow question: How to use ActiveAdmin on models using has_many through association?

Upvotes: 63

John Mount
John Mount

Reputation: 1

I have a has_one model, like this:

f.has_many :addresses do |a|
  a.inputs "Address" do
    a.input :street  ... etc.

While this correctly reflects our associations for Address (which is a polymorphic model) using f.has_one fails. So I changed over to has_many and all's well. Except now we have to prevent our users from creating multiple addresses for the same entity.

Upvotes: 0

rangalo
rangalo

Reputation: 5606

I guess you are looking for a form for a nested model. Take a look at following railscasts.

http://railscasts.com/episodes/196-nested-model-form-part-1

http://railscasts.com/episodes/197-nested-model-form-part-2

I cannot tell you much about active_admin, but I think this should not make a difference in handling the nested model.

Upvotes: -1

Related Questions