我使用Dragonfly将图像上传到与其他模特相关联的模型照片。例如:
MODEL:Post
class Post < ActiveRecord::Base
has_many :photos, dependent: :destroy
accepts_nested_attributes_for :photos, allow_destroy: true,
reject_if: lambda {|attributes| attributes['image'].blank?}
模特照片
class Photo < ActiveRecord::Base
extend Dragonfly::Model::Validations
dragonfly_accessor :image
dragonfly_accessor :image do
after_assign { |img| img.encode!('jpg', '-quality 80') }
end
即使我改变输入以同时上传多个文件,它也能正常工作
表格视图:
工作的:
<%= f.fields_for :photos do |photo| %>
<%= photo.file_field :image, class: "form-control" %>
<% end%>
不起作用:
<%= f.fields_for :photos do |photo| %>
<%= photo.file_field :image, class: "form-control", multiple: true, name: 'photo[image]' %>
<% end%>
如何将多个文件同时上传到关联模型?
谢谢!
更新
我试过了:
控制器。创建行动
@post = Post.new(seminovo_params)
params[:photos]['image'].each do |a|
@photo = @post.photos.create!(:image => a)
end
查看
<%= f.fields_for :photos, @post.photos.new do |photo| %>
<%= photo.file_field :image, :multiple => true, name: "photos[image][]" %>
答案 0 :(得分:0)
哟需要定义params并以这种方式获取这些参数
您的新方法应包含
def new
# Your new form object
@photo = @post.photos.build
end
在控制器方法中使用此
params[:photos]['avatar'].each do |a|
@photo = @post.photos.create!(:image => a)
end
您的表单应如下,
<%= form_for(@post, :html => { :multipart => true }) do |f| %>
<%= f.fields_for :photos do |p| %>
<div class="field">
<%= p.label :image %><br>
<%= p.file_field :image, :multiple => true, name: "photos[image][]" %>
</div>
<% end %>