Reputation: 91
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
Upvotes: 2
Views: 2405
Reputation: 91
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.
Upvotes: 2
Reputation: 1077
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
Upvotes: 1