Search code examples
ruby-on-railsimageruby-on-rails-5rails-activestorage

Rails 5 Active Storage: display multiple images


I am building a small CMS on Rails 5 to manage my online portfolio as picture book illustrator.

I am using Active Storage to upload and display images, but while the upload part works fine I still have some troubles with displaying them.

In my database I have a table called Works (which obviously represents the books that I work on), and each book has one single cover illustration and various illustrations.

In my Work model I defined the relationship as the Active Storage documentation suggests:

class Work < ApplicationRecord
   :has_many_attached :illustrations
end

In my controller I am using the with_attached_illustrations method in this way:

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

While in my view I am doing:

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

And this is the browser this is the output:

<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">]

Images are getting displayed fine, but I get that line with [#ActiveStorage::Attachment ... for every image that gets loaded.

What should I do in order to get rid of that?


Solution

  • You have this in your code:

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

    Get rid of the = sign in front of it, so it reads:

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