首页 > 解决方案 > Rails 5 Active Storage:显示多个图像

问题描述

我正在 Rails 5 上构建一个小型 CMS,以作为图画书插图画家来管理我的在线作品集。

我正在使用 Active Storage 上传和显示图像,但是虽然上传部分工作正常,但在显示它们时仍然存在一些问题。

在我的数据库中,我有一个名为Works(显然代表我正在研究的书籍)的表,每本书都有一个封面插图和各种插图。

在我的Work模型中,我将关系定义为 Active Storage 文档建议的

class Work < ApplicationRecord
   :has_many_attached :illustrations
end

在我的控制器中,我以这种方式使用with_attached_illustrations方法:

def show
    @project = Work.with_attached_illustrations.find(params[:id])
end

在我看来,我正在做:

<% if @project.illustrations.attached? %>
                <%= @project.illustrations.each do |illustration| %>
                        <%= image_tag(illustration, :class => "illustrations") %>
                <% end %>
            <% end %>

这是浏览器,这是输出:

<img class="illustrations" src="http://localhost:3000/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBDdz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--6766bc0bb57edf83ed29796e499d453019f10f3d/%C2%A901.jpg">
[#<ActiveStorage::Attachment id: 6, name: "illustrations", record_type: "Work", record_id: 9, blob_id: 6, created_at: "2019-07-17 01:55:04">]

[#ActiveStorage::Attachment ...图像显示得很好,但是对于每个加载的图像,我都会得到这条线。

我应该怎么做才能摆脱它?

标签: ruby-on-railsimageruby-on-rails-5rails-activestorage

解决方案


你的代码中有这个:

<%= @project.illustrations.each do |illustration| %>

去掉它前面的 = 符号,所以它显示:

<% @project.illustrations.each do |illustration| %>

推荐阅读