Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refile gem : multiple file uploads

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?

like image 239
the_ Avatar asked Jul 05 '15 00:07

the_


1 Answers

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:

  • [Refile::Attachment] object : Instance of a class which has an attached file.
  • [Symbol] name : The name of the attachment column

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.

like image 81
Florent Ferry Avatar answered Sep 19 '22 18:09

Florent Ferry