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)
如何使用多个图像上传来重新检索图像?
为了检索属于帖子的图像,您需要遍历图像数组.
<% @post.images.each do |image| %>
<%= attachment_image_tag(image, :file, :fill, 300, 300) %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
帮助者attachment_image_tag
:
所以在这里,@posts.images
持有一个image
对象数组.这是具有附件的对象.
class Image < ActiveRecord::Base
belongs_to :post
attachment :file
end
Run Code Online (Sandbox Code Playgroud)
然后,当您进行迭代时images
,您可以在image object
此处为帮助程序和附件列的名称提供帮助:file
.