我如何获得在Rails 5中工作的多个文件上传?
问题描述:
我在我的控制器,在轨道4,5工作以下罚款:我如何获得在Rails 5中工作的多个文件上传?
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
现在,升级到Rails 5后,这是行不通的。我强烈怀疑这是因为params is now an Object, rather than HashWithIndifferentAccess,但我不知道如何使多个文件上传再次工作。
尝试这样:
params.to_unsafe_h[:documents].map do |document|
但随后失败no implicit conversion of Symbol into Integer
为 if document[:upload]
部分。
关于如何在此方面前进的任何想法?
答
好吧,我不得不返工我的形式更“railsy”这在Rails的5工作,斯利姆(在new_multiple视图):
= 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
这里现在什么是控制器:
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
有可能是一个更好的方法来做到这一点,但现在这工作。
看来'document'是一个数组?你不能用'调试器'或某些日志记录来验证它吗? –