Rails5 Active Storage:显示多张图片

Rails 5 Active Storage: display multiple images

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

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

在我的数据库中,我有一个名为 Works 的 table(这显然代表了我从事的工作的书籍),每本书都有一个封面插图和各种插图。

在我的 Work 模型中,我定义了关系 as the Active Storage documentation suggests:

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 ... 的那一行。

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

你的代码中有这个:

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

把前面的=号去掉,就变成:

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

在循环中,第一行有“=”等号。删除它,你的循环将是这样的。

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