I have two models:
class Photo < ActiveRecord::Base
has_many :pictures, dependent: :destroy
accepts_nested_attributes_for :pictures
end
class Picture < ActiveRecord::Base
belongs_to :photo
has_attached_file :image, styles =>
{
:thumb => "200x200#"
}
end
and here is my form (pasting only the relevant nested part):
<%= simple_nested_for @photo, html: {multipart: true} do |f| %>
<%= f.simple_fields_for :picture_contents do |p| %>
<%= p.input :image, as: :file, label: "ADD PHOTO", :label_html => {class: "fileBt"}, :input_html => {class: "fileBt", id: "pictureInput", accept:"image/*"}, :item_wrapper_tag => :div, :item_wrapper_class => "col-md-4" %>
<div class="target"></div>
<%= a.link_to_remove "REMOVE", :class => "btn btn-danger btn-xs" %>
<div>
<%= f.link_to_add "ADD", :pictures, class: "fileBt" %>
</div>
<% end -%>
I want to be able to have a preview for each nested form. For now I can manage to display a preview for the first picture, but when I add a second nested form I can't display a preview for it. I need to be able to display a preview for each uploaded image.
This is the javascript I am using (credit goes to comment ):
$(function() {
$('#pictureInput').on('change', function(event) {
var files = event.target.files;
var image = files[0]
var reader = new FileReader();
reader.onload = function(file) {
var img = new Image();
console.log(file);
img.src = file.target.result;
$('.target').html(img);
}
reader.readAsDataURL(image);
console.log(files);
});
});
Any help would be greatly appreciated.
I'm not sure if this is the problem, but you shouldn't have multiple HTML elements with identical IDs. Try changing the JS so that it uses the class of file fields instead.
$(function() {
$('.fileBt').on('change', function(event) {
...
Note that you probably want to rename that class to something more meaningful and specific to image upload fields. For example ".photo-upload-field" would work :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.