Ruby
Rails
Rails4
activeadmin

Rail 4.1でActiveAdminとhas_manyなnested form

More than 3 years have passed since last update.

画像アップロードがCarrierwaveなのは使ってるのに読み替えてもらえれば。

Gemfile
# gem 'formtastic' , github: 'justinfrench/formtastic'
# gem 'ransack'    , github: 'activerecord-hackery/ransack', branch: 'rails-4.1'
# gem 'polyamorous', github: 'activerecord-hackery/polyamorous'
# 上の3つは最近のバージョンではいらなくなったね!
gem 'activeadmin', github: 'gregbell/active_admin'
gem 'carrierwave'
app/models/post.rb
def Post < ActiveRecord::Base
    has_many :images, dependent: :destroy
    accepts_nested_attributes_for :images, allow_destroy: true
end
app/models/image.rb
def Image < ActiveRecord::Base
    belongs_to :post
    mount_uploader :image, ImageUploader
end
app/admin/post.rb
ActiveAdmin.register Post do
    permit_params :title, :body, :images_attributes => [:image, :_destroy, :id]

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

        f.inputs do
            f.has_many :images, heading: 'Images', allow_destroy: true, new_record: true do |a|
            a.input :image, :hint => a.object.image.nil? ? a.template.content_tag(:span, "no image yet") : a.template.image_tag(a.object.image.thumb.url)
      end
    end

    f.actions
  end