1
votes

I'm following the rails ActiveStorage guide. I've successfully saved the image to the blob table in the local database (the attachment table is empty). But I can't seem to show it in the view:

<%= url_for(@comment.images) if @comment.images %>

does not work nor does:

     <% @comments.each do |c| %>
        <%= c.body %>

        <%= url_for(c.images) if c.images %>

      <% end %>

Showing other values of comment works, so this is specific to the images. I've also tried adding .url to "images." And I've tried image_tag instead of url_for. And looping through the images. And image_tag url_for (instead of using just one of them). And using representation. No luck in all of these cases. I'd really appreciate any help.

And my model

  has_many_attached :images

application.js

//= require activestorage


import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"


Rails.start()
Turbolinks.start()
ActiveStorage.start()

controller



    private
        def comment_params
            params.require(:comment).permit(:body, images: [])
    end



2
Are those images representable? could you please check the result for @comment.images.first.representable?Sampat Badhe
Have you looked into the section for how Displaying Images, Videos, and PDFs from Active Storage Overview documentation ?Sampat Badhe
@SampatBadhe Hey Sampat, thank you for your comment. I got this error: undefined method `representable' for nil:NilClass. I also tried <%= image_tag i.representation(resize: '500x500') %> but nothing showed. ( "i" since I was looping through them)amazingbot
Are you sure images are exists for comment? Could you please check @comment.images.attached? returns true or false?Sampat Badhe
@SampatBadhe Thank you -- you're exactly right, it returns false. What does this mean? The blob table shows the images, so I just assumed ("metadata" is empty though).amazingbot

2 Answers

1
votes

The solution was to change file upload form from

<%= form.file_field :images, multipart: true, direct_upload: true %>

to

<%= form.file_field :images, multiple: true, direct_upload: true %>

It was not uploading before, and somebody had suggested switching to "multipart." It solved the uploading in appearance but it was not attaching the image.

I guess the uploading in appearance also works now because I tweaked something as I frantically tried multiple things.

Now the attachments table is populating with images. Before only the blob table was populating.

0
votes

You have specified has_many_attached, so @comment.images will contain an array of images, So the following code will display the first image of your comment.

     <%= image_tag(@comment.images.first) if @comment.images.attached? %>

If you want to display all images you can iterate through @comment.images array and display each image