ActiveAdmin forms with has_many - belongs_to relationships?

agente_secreto picture agente_secreto · Oct 31, 2011 · Viewed 24.1k times · Source

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

Answer

jfedick picture jfedick · Nov 7, 2011

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?