Refile gem:多个文件上传

the*_*he_ 13 ruby ruby-on-rails image file refile

我正在使用Refile with Rails 4.我正在按照他们的教程进行多个图像上传.每个帖子可以有多个图像.我的模型看起来像这样:

Post.rb:

has_many :images, dependent: :destroy
accepts_attachments_for :images, attachment: :file
Run Code Online (Sandbox Code Playgroud)

Image.rb:

belongs_to :post
attachment :file
Run Code Online (Sandbox Code Playgroud)

我可以上传文件,使用:

<%= f.attachment_field :images_files, multiple: true, direct: true, presigned: true %>
Run Code Online (Sandbox Code Playgroud)

但是当我尝试检索如下图像时:

 <%= attachment_image_tag(@post.images, :file, :small) %>
Run Code Online (Sandbox Code Playgroud)

我收到错误:

undefined method file for #<Image::ActiveRecord_Associations_CollectionProxy:0x007fbaf51e8ea0>
Run Code Online (Sandbox Code Playgroud)

如何使用多个图像上传来重新检索图像?

Flo*_*rry 5

为了检索属于帖子的图像,您需要遍历图像数组.

<% @post.images.each do |image| %>
  <%= attachment_image_tag(image, :file, :fill, 300, 300) %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

帮助者attachment_image_tag:

  • [Refile :: Attachment]对象:具有附加文件的类的实例.
  • [符号]名称:附件列的名称

所以在这里,@posts.images持有一个image对象数组.这是具有附件的对象.

class Image < ActiveRecord::Base
  belongs_to :post
  attachment :file
end
Run Code Online (Sandbox Code Playgroud)

然后,当您进行迭代时images,您可以在image object此处为帮助程序和附件列的名称提供帮助:file.