Ruby on Rails 嵌套模型-多次上传
示例
如果您要创建多个上传,则可能要做的第一件事是创建新模型并建立关系
假设您要为Product模型制作多个图像。创建一个新模型并使其成为belongs_to您的父模型
rails g model ProductPhoto #product.rb has_many :product_photos, dependent: :destroy accepts_nested_attributes_for :product_photos #product_photo.rb belongs_to :product mount_uploader :image_url, ProductPhotoUploader #确保包括上载器(载波示例)
必须使用accepts_nested_attributes_for,因为它允许我们创建嵌套表单,因此我们可以从单个表单上载新文件,更改产品名称和设置价格
接下来,在视图中创建表单(编辑/创建)
<%= form_for @product, html: { multipart: true } do |product|%>
<%=product.text_field:price # just normal type of field %>
<%=product.fields_for:product_photos do |photo| # nested fields %>
<%=photo.file_field:image, :multiple => true, name: "product_photos[image_url][]" %>
<% end %>
<%=p.submit"Update", class: "btn" %>
<% end %>控制器没什么特别的,如果您不想创建一个新控制器,只需在产品控制器中创建一个新控制器即可。
#创建动作
def upload_file
printer = Product.find_by_id(params[:id])
@product_photo = printer.prodcut_photos.create(photo_params)
end
#强大的参数
private
def photo_params
params.require(:product_photos).permit(:image)
end在视图中显示所有图像
<% @product.product_photos.each do |i| %>
<%= image_tag i.image.url, class: 'img-rounded' %>
<% end %>