2016-07-14 9 views
1

Ich habe folgend in meinem Controller, der in Rails fein gearbeitet 4:Wie kann ich mehrere Datei-Uploads in Rails 5 arbeiten lassen?

def create_multiple 
    params[:documents].map do |document| 
    if document[:upload] 
     doc = Document.new 
     doc.upload = document[:upload] 
     doc.category_id = @category.id 
     doc.save 
    end 
    end 
    redirect_to @category, notice: 'Documents saved' 
end 

Jetzt, nach dem Upgrade 5 bis Rails, funktioniert es nicht. Ich vermute stark, dass dies daran liegt, dass params is now an Object, rather than HashWithIndifferentAccess, aber ich kann nicht herausfinden, wie Sie den Upload von mehreren Dateien wieder tun.

dies versucht:

params.to_unsafe_h[:documents].map do |document| 

Aber dann schlägt es mit no implicit conversion of Symbol into Integer für den if document[:upload] Teil.

Irgendwelche Ideen, wie ich weitermachen kann?

+0

Es scheint, dass 'Dokument' ein Array ist? Können Sie das nicht mit einem 'Debugger' oder etwas Logging validieren? –

Antwort

0

Ok, hatte ich meine Form zu überarbeiten mehr "railsy" zu sein für diese 5 in Rails zu arbeiten, in dünne (in der new_multiple Ansicht):

= form_tag create_multiple_category_documents_path(@category), multipart: true do 
    .row.bottom30 
    - @documents.each_with_index do |document, ndx| 
     = fields_for 'documents[]', document, index: ndx do |f| 
     .col-xs-12.col-sm-6.col-md-4.bottom30 
      => f.label :title 
      = f.text_field :title, class: 'form-control' 
      = f.file_field :upload 

Und hier ist das, was in der Steuerung jetzt ist:

def new_multiple 
    @documents = 20.times.map { @category.documents.build } 
end 

def create_multiple 
    params[:documents].each do |num, document| 
    unless document[:upload].blank? 
     doc = Document.new 
     doc.upload = document[:upload] 
     doc.category_id = @category.id 
     doc.save 
    end 
    end 
    redirect_to @category, notice: 'Documents saved' 
end 

Es gibt wahrscheinlich einen besseren Weg, dies zu tun, aber das funktioniert für jetzt.