Nested model - multiple uploads
suggest changeTo attach several uploads, add a model and the associations.
For several images on Product, generate the photo model and make it belongs_to the parent:
rails g model ProductPhoto product:references image:string
# app/models/product.rb
class Product < ApplicationRecord
has_many :product_photos, dependent: :destroy
accepts_nested_attributes_for :product_photos
end
# app/models/product_photo.rb
class ProductPhoto < ApplicationRecord
belongs_to :product
mount_uploader :image, ProductPhotoUploader
end
accepts_nested_attributes_for is required for a nested form that saves photos with the product. The uploader column here is image, the same name file_field and image.url use.
Build at least one child in the controller (@product.product_photos.build) or fields_for renders nothing. file_field already sets the multipart form and the product[product_photos_attributes][0][image] parameter name. Do not also pass name: or :multiple; that replaces the nested-attribute name, and one fields_for row is one record.
<%= form_for @product do |product| %>
<%= product.text_field :price %>
<%= product.fields_for :product_photos do |photo| %>
<%= photo.file_field :image %>
<% end %>
<%= product.submit "Update", class: "btn" %>
<% end %>
Permit the nested hash on the product, and update the product. A separate upload action has to read that same key. prodcut_photos and find_by_id do not match this form.
def update
@product = Product.find(params[:id])
@product.update(product_params)
end
private
def product_params
params.require(:product).permit(:price, product_photos_attributes: [:image])
end
Display the images:
<% @product.product_photos.each do |photo| %>
<%= image_tag photo.image.url, class: "img-rounded" %>
<% end %>