Skip to content

Nested model form image upload

houen edited this page Jan 26, 2012 · 2 revisions

Here's a way to get uploads working with a nested form model. Here we have a User model that belongs_to Media, and Media belongs_to Image and belongs_to Media. Thus, User has_one :image, :through => :media and has_one :video, :through => :media


form :html => { :multipart => true } do |f|
  f.inputs "General" do
    f.input :name
  end

  f.inputs "Image or Video", :for => [:media, f.object.media || Media.new ] do |fm|
    fm.inputs "Image", :for => [:image, fm.object.image || Image.new] do |fmi|
      fmi.input :file, :for => :image, :as => :file, :hint => f.template.image_tag(f.object.media.image.url(:cropped))
    end
    fm.inputs "Video", :for => [:video, fm.object.video || Video.new] do |fmv|
      fmv.input :url
    end
  end
end