单一模型的

时间:2018-05-04 18:18:15

标签: ruby-on-rails carrierwave

我已经在本教程https://kolosek.com/carrierwave-upload-multiple-images/的帮助下创建了一个库模块,现在我想再添加一个图像属性,将主图像添加到同一模型中。所以我提出再创建一个上传器,但我对如何调用控制器可以让任何人帮助我感到困惑?

我的代码如下所示:

MOdel代码:

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

gallery_controller.rb

 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]['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   

图像控制器代码:

class ImagesController < AdminController
 def image_params
   params.require(:image).permit(:gallery_id, :slideshow_id,:image, :avatar)
 end
end

form.html.erb

<%= form.fields_for :images do |p| %>
 <div class="field">
   <%= form.label :master_image, class: "col-2 col-form-label" %>
  <%= form.file_field :avatar, :multiple => true, name: "images[avatar][]" %>
  </div>
<% end %>
<%= form.fields_for :images do |p| %>
  <div class="field">
    <%= form.label :image, class: "col-2 col-form-label" %>
    <%= form.file_field :image, :multiple => true, name: "images[image][]" %>
  </div>
<% end %>

我很难修改图库控制器创建部分。

1 个答案:

答案 0 :(得分:1)

如果您有2个上传者,可以在create方法中添加2次图片

params[:images]['image'].each do |a|
  @gallery.images.create!(:image => a, :gallery_id =>  @gallery.id)
end
params[:images]['avatar'].each do |a|
  @gallery.images.create!(:avatar => a, :gallery_id =>  @gallery.id)
end

但我觉得它有点冗长,如果您不想在表单中上传任何图片,那么它并没有真正阻止(返回params[:images]['...']无)

您的表单对form.fields_for不正确。它是:

<%= form.fields_for :images_attributes 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_attributes 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 %>