使用carrierwave的单个模型的多图像上传器

时间:2018-05-05 10:44:49

标签: ruby-on-rails ruby ruby-on-rails-3 carrierwave

我创建了一个图库模块,我为单个模型添加了两个上传器。代码工作正常,但当我上传多个图像并尝试编辑,我有多个选项上传相同的图像。我该如何解决这个问题?我们可以为同一模型使用两个上传器吗?或者我们有其他方法吗?

型号代码:

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

class Gallery < ApplicationRecord
  has_many :images
  accepts_nested_attributes_for :images
end

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 Controller code:

class ImagesController < AdminController
  def image_params
   params.require(:image).permit(:gallery_id, :slideshow_id,:image, :avatar)
  end
 end
[![edit page ][1]][1]
form page:
 <%= 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 %>

0 个答案:

没有答案