简体   繁体   English

使用Carrierwave和Formtastic上传Rails 3文件

[英]Rails 3 file upload with Carrierwave and Formtastic

I have a Product with many Photos. 我有一个包含许多照片的产品。 The relationship is this way: 这种关系是这样的:

product.rb 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 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... 我正在使用Friendly_Id,ActiveAdmin,Globalize3,也许它可能与它们有一些关系,这是我与Rails的第一个项目,现在我不知道可能是什么...

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. 您的问题是您在模型中将photos声明为has_many关联,并在视图中将其声明为单个文件输入。 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. 循环遍历产品中的每张照片,并为每个照片显示文件输入字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM