Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created a gallery module with the help of this tutorial https://kolosek.com/carrierwave-upload-multiple-images/ and now I wanted to add one more image attribute has a master image to the same model. So I thot of creating one more uploader. The code works fine but when I upload multiple images and try to edit that the edit form shows the upload image attribute multiple times. what is wrong in my code?

What I have tried:

gallery controller code :
class GalleriesController < AdminController   
  def index
    @galleries = Gallery.all
  end

  def show
   @images = @gallery.images.all
  end

  def new
   @gallery = Gallery.new
   @image = @gallery.images.build
  end 

  def create
   @gallery = Gallery.new(gallery_params)
   respond_to do |format|
   if @gallery.save
     params[:images]['avatar'].each do |a|
       @gallery.images.create!(:avatar => a, :gallery_id =>  @gallery.id)
     end
     params[:images]['image'].each do |a|
      @images = @gallery.images.create!(:image => a, :gallery_id =>  @gallery.id)
    end
     format.html { redirect_to @gallery, notice: 'Gallery was successfully created.' }
     format.json { render :show, status: :created, location: @gallery }
   else
     format.html { render :new }
     format.json { render json: @gallery.errors, status: :unprocessable_entity }
   end
 end
end

def gallery_params
  params.require(:gallery).permit(:title, :details, :status, images_attributes:[:id, :gallery_id, :image, :avatar])
end   


Image Model
class Image < ApplicationRecord
  belongs_to :gallery 
  mount_uploader :image, ImageUploader
  mount_uploader :avatar, AvatarUploader
end


Gallery model:
class Gallery < ApplicationRecord
 has_many :images
 accepts_nested_attributes_for :images
end


form.html.erb
HTML
<%= form.fields_for :images do |p| %>
 <div class="field">
   <%= p.label :master_image, class: "col-2 col-form-label" %>
   <%= p.file_field :avatar, :multiple => true, name: "images[avatar][]" %>
  </div>
<% end %>
<%= form.fields_for :images do |p| %>
  <div class="field">
    <%= p.label :image, class: "col-2 col-form-label" %>
    <%= p.file_field :image, :multiple => true, name: "images[image][]" %>
  </div>
<% end %>
Posted
Updated 4-May-18 23:12pm
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900