3

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...

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you a lot for your response. The one before the edit worked fine: f.semantic_fields_for :photos do |ff| ff.input :photo, as: :file end
But doesn't show any file input field if there is no photo. I just wanted 1 file input field so it would create a new photo.
Then you must build a photo instance in your controller. eg. @product.photos.build The form cannot display what does not exist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.