【问题标题】:Rails 4 Multiple file upload using carrierwave and nested formsRails 4 使用carrierwave和嵌套表单上传多个文件
【发布时间】:2016-01-06 09:36:52
【问题描述】:

我有一个包含许多图像的目录项,并尝试使用嵌套表单和载波通过一个请求上传所有图像。我也使用响应器、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

【问题讨论】:

    标签: ruby ruby-on-rails-4 file-upload carrierwave nested-forms


    【解决方案1】:

    所以,我终于找到了答案。我的 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 中以复数形式使用了 images_attributes

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

    仅此而已。

    【讨论】:

    • name: "item[images_attributes][][image]" 中额外的 [] 让我大吃一惊 ?
    【解决方案2】:

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

    【讨论】:

    • 不,还是一样的结果。项目已保存,但图像被忽略。
    • 仍然不起作用,但我发现 :item:imagesparam的两个独立元素> 哈希,那我的嵌套表单实现会不会有问题?
    猜你喜欢
    • 1970-01-01
    • 2014-05-22
    • 2015-11-21
    • 2014-02-20
    • 2016-04-05
    • 2013-02-24
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    相关资源
    最近更新 更多