2

I might be missing something silly but I can't get multiple embedded photo files into a form

Models

class Product
   include Mongoid::Document

   embeds_many :photos, cascade_callbacks: true
end

class Photo
   include Mongoid::Document

   embedded_in product, :inverse_of => :photos
   field :image_filename
   mount_uploader :image, ImageUploader
end

Controller - products_controller.rb

def new
   @product = Product.new
   3.times { @product.photos.build }
end

Form

Then I do the form with

fields_for @product.photos do |photo|
   <%= photo.file_field :image %>
end

The problem is only 1 photo is showing up but I am building 3 in the controller. The count for @product.photos.count is 0 even after i build 3 in memory. Am I missing something?

Jeff Locke
  • 617
  • 1
  • 6
  • 17
  • Similar to this, I think you need the product to "build" first. Basically, @product doesn't exist yet (you didn't "save" it) so any collection-based associations will also return "nil" http://stackoverflow.com/questions/783584/ruby-on-rails-how-do-i-use-the-active-record-build-method-in-a-belongs-to-rel – Dominic Tancredi Jul 25 '12 at 12:36
  • @product is already created in memory through the Product.new call. This is very common in ActiveRecord but for some reason it's not working within Mongoid and embedded documents – Jeff Locke Jul 25 '12 at 12:40

1 Answers1

3
fields_for @product.photos do |photo|
   <%= photo.file_field :image %>
end

should be

fields_for :photos do |photo|
   <%= photo.file_field :image %>
end
Jeff Locke
  • 617
  • 1
  • 6
  • 17