【问题标题】:Rails 5 Active Storage: display multiple imagesRails 5 Active Storage:显示多个图像
【发布时间】:2019-07-17 07:08:33
【问题描述】:

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

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

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

在我的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 ... 得到那条线。

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

【问题讨论】:

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


    【解决方案1】:

    你的代码中有这个:

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

    去掉前面的=号,改为:

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

    【讨论】:

    • ...不敢相信我没有注意到它!现在它完美地工作了。谢谢!
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      相关资源
      最近更新 更多