Search code examples
ruby-on-railsrubyrails-activestorage

Is there a way to loop through many attached images using active storage


I have installed active storage and I want a Post class or model to have one or many images so I created an association like below:

class Post < ApplicationRecord
   has_many_attached :images
end

I can create a post and I have allowed the images in the parameters and I have enabled multiple uploads and the post can be created successfully but when I want to iterate the images on the view like below I get nothing;

<% @post.images.each do |image| %>
  <%= image_tag(image) %>
<%end%>

When I try to just display one image without looping like below I get an error saying Can't resolve image into URL: undefined method to_model'`.

<%= image_tag(@post.images) %>

So far that is what I have tried and when I just display the @post.images in an embedded ruby I can get some information like below that indeed the images are there.

Active storage details

Is there anything am doing wrong?


Solution

  • I implemented this previously by doing it this way.

    class Post < ApplicationRecord
     has_many_attached :images
    end
    

    The images for your post should included in the params as such:

    def car_params
      params.require(:car).permit(:name, :description, :comments, images:[])
    end
    

    Then in the views, I looped through the images this way:

    <% if @post.images.attached? %>
      <% @car.images.each do |image| %>
       <li>
        <button type="button" >
          <%= image_tag(url_for(image)) %>
        </button>
       </li>
      <% end %>
     <% end %>
    

    If you want to select one image without looping, then you can select by the index.

    <%= image_tag(@post.images[0]) %>
    

    If you seek to loop through, go ahead with the url tag as that works better.