Rails 4 使用载波和嵌套形式的多文件上传

Rails 4 Multiple file upload using carrierwave and nested forms

我有一个包含许多图像的目录项,我正在尝试使用嵌套表单和载波通过一个请求上传所有图像。我还使用响应者、haml 和简单形式。 所以,它是这样的:

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

尝试将您的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

所以,我终于找到了答案。我的 html 表格有一些错误。 第一个错误非常明显。我用了

= simple_fields_for :images do |image|

而不是

= f.simple_fields_for :images do |image|

_form.html.haml 我读完这篇文章后发现的第二个 article. 所以我将我的嵌套形式更改为:

= 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:[=15 中以复数形式使用了 images_attributes =]

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

仅此而已。