Rails Carrierwave 添加更多文件 未定义的方法"标识符"



我正在尝试实现添加更多文件并使用carrierwave gem删除单个文件。我已经按照我在这里找到的说明进行操作。但是当我尝试添加更多文件时,旧文件会变得NUL并因某种原因被删除。没有出现错误,但是如果我查看控制台,我会得到这个:

SQL (0.5ms)  UPDATE "items" SET "images" = $1, "updated_at" = $2 WHERE "items"."id" = $3  [["images", "{NULL,NULL,image5.jpg,image6.jpg}"], ["updated_at", "2018-10-18 07:58:52.685554"], ["id", 85]] (0.4ms)  COMMIT

此外,当我尝试删除文件时,没有任何反应。没有出现错误,文件仍然保持原样,但是如果我查看控制台,我会得到这个:

SQL (0.6ms)  UPDATE "items" SET "images" = $1, "updated_at" = $2 WHERE "items"."id" = $3  [["images", "{NULL,NULL,image5.jpg,image6.jpg}"], ["updated_at", "2018-10-18 08:00:29.641571"], ["id", 85]] (0.4ms)  COMMIT

我不知道为什么会发生这种情况,我一直在尝试解决这个问题一段时间,所以任何关于如何完成这项工作的帮助将不胜感激。

这是我的设置:

我将此列添加到项目模型中:

add_column :items, :images, :string, array: true, default: []

这些是我拥有的路线:

match 'store/item/:id'=> 'attachments#destroy', :via => :delete, :as => :remove_item_image
post "store/item/:id"=> "attachments#create", :as => :create_item_image

控制器:

class AttachmentsController < ApplicationController
before_action :set_item
def create
add_more_images(images_params[:images])
flash[:error] = "Failed uploading images" unless @item.save
redirect_back fallback_location: root_path
end
def destroy
remove_image_at_index(params[:id].to_i)
flash[:error] = "Failed deleting image" unless @item.save
redirect_back fallback_location: root_path
end
private
def set_item
@item = Item.find(params[:id])
end
def add_more_images(new_images)
images = @item.images
images += new_images
@item.images = images
end
def remove_image_at_index(index)
remain_images = @item.images # copy the array
deleted_image = remain_images.delete_at(index) # delete the target image
deleted_image.try(:remove!) # delete image from S3
@item.images = remain_images # re-assign back
end
def images_params
params.require(:item).permit({images: []}) # allow nested params as array
end
end

这是我循环浏览图像并添加删除链接的视图:

<% @item.images.each_with_index do |img, index| #grab the index %>
<%= image_tag(img.url(:mini)) %>
<%= link_to "Remove", remove_item_image_path(@item, index: index), data: { confirm: "Are you sure you want to delete this image?" }, :method => :delete %>
<% end %>

这是添加更多图像的表单:

<%= form_for @item, url: create_item_image_path(@item), method: :post , :html => {:id => "form", :multipart => true } do |f| %>
<%= f.file_field :images, multiple: true %>
<%= f.submit 'Add more files' %>
<% end %>

更新 1

当我尝试从rails console手动添加本地图像时,我这样做:

@item = Item.find(85)
@item.images << [File.open("#{Rails.root}/app/assets/images/no-image.jpg", 'rb')]

新的本地映像正在添加到数组中,但是当我执行此操作时@item.save出现以下错误:

NoMethodError: undefined method `identifier' for #<Array:0x007fd2536ccd98>
from (irb):4

有什么想法吗?

您正在向 @item.images 关联添加一个数组,它需要一个文件并尝试对其调用identifier。仅设置文件:

@item.images << File.open("#{Rails.root}/app/assets/images/no-image.jpg", 'rb')

如果您想一次添加多个图像,您可以在循环中执行此操作,或者@image.images对象有一些添加多个图像的方法(我在文档中找不到它,但我想有一个(。在您提供的链接上,它确实:

images += new_images

最新更新