Search code examples
ruby-on-railsruby-on-rails-3carrierwaveformtastic

Rails 3 file upload with Carrierwave and Formtastic


I have a Product with many Photos. The relationship is this way:

product.rb

class Product < ActiveRecord::Base
  has_many :photos, :dependent => :destroy
  attr_accessible :translations_attributes, :active, :category_id, :photos
  accepts_nested_attributes_for :translations, :photos

photo.rb

class Photo < ActiveRecord::Base
  attr_accessible :photo, :product_id
  belongs_to :attachable
  mount_uploader :photo, PhotoUploader

and the form looks like this:

form(:html => { :multipart => true }) do |f|
f.inputs "Details" do
  f.input :active
  f.input :category, :include_blank => false
end

f.inputs "Photos" do
    f.input :photos, :as => :file
end

f.buttons

end

The problem is that I get this error when creating/updating the product with a file attached:

undefined method `each' for #<ActionDispatch::Http::UploadedFile:0x007f93c8549828>

I found a question with the same error here, but even trying their solution still have the same problem.

I'm using Friendly_Id, ActiveAdmin, Globalize3, maybe it could have some relationship with them, this is my first project with Rails and right now I don't know what could be...


Solution

  • Your problem is that you're declaring photos as a has_many association in your model, and declaring it as a single file input in your view. Many or one, take your pick :)

    What you're probably trying to do is have photos as a nested model in your Product form - something like so:

    semantic_form_for @product do |f|
      f.semantic_fields_for :photos do |ff|
        ff.input :photo, as: :file
    

    To loop over each of the photos in your product, and display a file input field for each.