I'm using Refile with Rails 4. I'm following their tutorial for multiple image upload. Each Post can have multiple Images. My models look like this:
Post.rb:
has_many :images, dependent: :destroy
accepts_attachments_for :images, attachment: :file
Image.rb:
belongs_to :post
attachment :file
I can upload files, fine by using:
<%= f.attachment_field :images_files, multiple: true, direct: true, presigned: true %>
but when I try to retrieve an image like:
<%= attachment_image_tag(@post.images, :file, :small) %>
I get the error:
undefined method file for #<Image::ActiveRecord_Associations_CollectionProxy:0x007fbaf51e8ea0>
How can I retrieve an image with refile using multiple image upload?
In order to retrieve images who belongs to a post, you need to iterate through the array of images.
<% @post.images.each do |image| %>
<%= attachment_image_tag(image, :file, :fill, 300, 300) %>
<% end %>
The helper attachment_image_tag
take:
So here, @posts.images
holds an array of image
object. It's that object who has an attached file.
class Image < ActiveRecord::Base
belongs_to :post
attachment :file
end
Then when you iterate images
, you give to the helper the image object
, and the name of the attachment column, here :file
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With