0

I've been trying to get multi image uploads working on a nested model in rails. I've been using the s3_file_field gem, which can be found here.

I've created a gist which shows the relevant parts of my code which is available here.

When I try to upload two images, both images are uploaded to S3, but only one Image object is saved to the database. I need to find a way to create an Image object for each image that is uploaded to S3.

Sam
  • 7,252
  • 16
  • 46
  • 65
  • Nested models and forms make me cringe. When you have that level of complexity, you should probably create a new object to handle it. Try form objects - see another answer here: http://stackoverflow.com/a/25298020/1448966 – A Fader Darkly Aug 19 '14 at 09:28

1 Answers1

0

i raised a similar question here....use paperclip >= 4 along with s3 to make this work.

class Image < ActiveRecord::Base
  has_many :image_photos , :dependent => :destroy
  accepts_nested_attributes_for :image_photos, :reject_if => lambda { |a| a[:avatar].blank? }, :allow_destroy => true
end


class ImagePhoto < ActiveRecord::Base
 belongs_to :image
 has_attached_file :avatar,
  :styles => {:view => "187x260#"},
  :storage => :s3,
  :s3_permissions => :private,
  :s3_credentials => S3_CREDENTIALS
 attr_accessible :image_id,:avatar,:avatar_file_name,:avatar_content_type,:avatar_file_size,:avatar_updated_at
 validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
 validates_presence_of :avatar
end

in controller

 def new
if current_or_guest_user.pic_categories.present?
 @image = Image.new
 #3.times {@image.image_assets.build} # added this
 @image.image_photos.build

end 

 def create
@image = Image.new(params[:image])
@image.user_id = current_or_guest_user.id
 if @image.save
   if params[:image_photos][:avatar]
     params[:image_photos][:avatar].each { |image|
       @image.image_photos.create(avatar: image)
       }
      end
@image.create_activity key: 'image.create', owner: current_or_guest_user
end

_form.html.erb

<%= form_for(@image,:html=>{:multipart => true,:remote=>true,:class=>"form-horizontal",:role=>"form"}) do |f |%>
 <%= f.fields_for :image_photos do |builder| %>
<% if builder.object.new_record? %>
   Upload picture
  <!-- to add multiple images--> 
  <%= builder.file_field :avatar,:multiple=>"true",:name=>"image_photos[avatar]  []",:class=>"opacity"%></a>
 <%end%>


<%end%>
Community
  • 1
  • 1
Milind
  • 4,535
  • 2
  • 26
  • 58