ActiveStorage image display count

Beginner of programming. I think there is something wrong with how to ask questions, but thank you.

In order to learn Rails, I have created an article posting app by myself.
I would like to ask about the number of images displayed on the article list page because I could not implement it as intended.

  • You can post articles
  • You can post images (multiple photos)
  • Edit/delete articles (not implemented)
  • User registration (not implemented)
Development environment
  • ruby ​​'2.5.1'
  • rails '5.2.3'
I want to solve

When displaying posted articles on the list page, posted images and titles are displayed.
There is no problem when you post a single image, but when you post multiple images, the displayed images and titles will be displayed.
I would like to implement this display so that only one sheet can be displayed, but it does not work well.

Applicable source code
    [email protected] articles.each do | article |
      = link_to article_path (article), class: "text-dark text-decoration-none" do
              -article.images.each do | image |
                = image_tag image.variant (resize: "150x150"). processed, class: "article-list-img"
                = article.title

Because ActiveStorage is used, the submitted images are stored in the array, so we proceeded with the implementation of an image that can be extracted from the array as shown below, but it cannot be extracted successfully.

# Example ①
= image_tag image [0] .variant (resize: "150x150"). processed, class: "article-list-img"
# Example ②
= image_tag image.first.variant (resize: "150x150"). processed, class: "article-list-img"

I tried as much as possible by myself and tried and errored, but I can not solve it, so I would like advice on corrections and reference articles. Thank you in advance.

  • Answer # 1

    -article.images.each do | image |
          = image_tag image.variant (resize: "150x150"). processed, class: "article-list-img"

    Showing all images in a loop

    -if article.images.count>0
         = image_tag article.images.first.variant (resize: "150x150"). processed, class: "article-list-img"

    I don't know which one to display, so I'd like to display only the first one.

Related articles