Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 436
agente_secreto Avatar asked Oct 31 '11 18:10

agente_secreto


2 Answers

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?

like image 138
jfedick Avatar answered Oct 29 '22 19:10

jfedick


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)

like image 37
MegaCasper Avatar answered Oct 29 '22 19:10

MegaCasper