Rails 4使用carrierwave和嵌套表单进行多文件上传

3
我有一个目录项目,其中包含许多图像,并尝试使用嵌套表单和CarrierWave通过一个请求上传所有内容。我还使用了responders、haml和simple form。因此,代码大致如下:
item.rb
class Item < ActiveRecord::Base
  has_many :images, dependent: :destroy
  accepts_nested_attributes_for :images
end

image.rb

class Image < ActiveRecord::Base
  belongs_to :item
  mount_uploader :image, ImageUploader
end

_form.html.haml

= simple_form_for(@item, :html => {:multipart => true }) do |f|
  = f.error_notification

  .form-inputs
    = f.input :name
    = f.input :description
    = f.input :price

  = simple_fields_for :images do |image|
    = image.file_field :image, multiple: true

  .form-actions
    = f.button :submit

items_controller.rb

...
def new
  @item = Item.new
  respond_with(@item)
end

def create
  @item = Item.new(item_params)
  @item.save
  respond_with(@item)
end
...
def item_params
  params.require(:item).permit(
    :name, :description, :price,
    image_attributes: [:image]
  )
end

我对Rails还很陌生,它显然没有按照我想要的方式运作。它保存了项目,但完全忽略了所有图像。
因此,我想知道是否有任何方法可以在不使用类似于...的结构的情况下实现我的目标。
def create
  @item = Item.new(item_params)
  params[:images].each do |image|
    img = Image.new
    img.image = image
    @item.images << img
  end
  @item.save
  respond_with(@item)
end
2个回答

5
所以,最终我找到了答案。我的 HTML 表单中有一些错误。 第一个错误非常明显。我使用了

标签。
= simple_fields_for :images do |image|

替代

= f.simple_fields_for :images do |image|

_form.html.haml 文件中, 我读完这篇文章后发现了第二个问题。 所以我将嵌套表单更改为以下形式:

= f.simple_fields_for :images, Image.new do |image_form|
    = image_form.file_field :image, multiple: true,
                   name: "item[images_attributes][][image]"

正如Pavan的建议,我在我的items_controller.rb中使用了复数形式的images_attributes

def item_params
  params.require(:item).permit(
    :name, :description, :price,
    images_attributes: [:image]
  )
end

And thats all.


name: "item[images_attributes][][image]" 中的额外 [] 是让我困惑的地方。 - Dan Tappin

0

尝试将您的new方法更改为以下方式

def new
  @item = Item.new
  @item.images.build
  respond_with(@item)
end

另外,由于您正在上传多张图片,请将您的item_params更改为以下内容

def item_params
  params.require(:item).permit(:name, :description, :price, images_attributes: [:image => []])
end

不行,结果还是一样。项目已保存,但图片被忽略了。 - Oviron
仍然无法工作,但我发现:item:imagesparam哈希的两个单独元素,所以我的嵌套表单实现可能有问题? - Oviron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接