问题
I'm building a Rails app to store products, so a product has_many images. I can upload up to 4 images when I create a New record, this is the New Action in Products controller:
def new
@product = Product.new
4.times { @product.images.build }
end
And this is the view:
<%= form_for @product, :html => {:multipart => true} do |f| %>
.
.
.
.
<%= f.fields_for :images do |builder| %>
<% if builder.object.new_record? %>
<p>
<%= builder.label :image, "Image File" %>
<%= builder.file_field :image %>
</p>
<% end %>
<% end %>
<% end %>
And in the Product's model I allowed nested attributes:
accepts_nested_attributes_for :images, :reject_if => lambda { |t| t['image'].nil? }
Everything is fine up to this point. My question is: How can I update the images that belongs to the product? For example: If the user creates a new record with 2 or 3 images, then the user should be able to edit the product description and its images. So far my Edit action is defined this way:
def edit
@product = Product.find(params[:id])
end
def update
@product = Product.find(params[:id])
if @product.update(product_params)
redirect_to :root
else
render 'edit'
end
end
I'm using Paperclip to upload images. I tried doing the same thing I did the the New Action, but instead of updating the images, it just uploaded new ones.
EDIT:
product_params:
def product_params
params.require(:product).permit(:title, :info_item, :description, :price, :subcategory_id, :category_id, :images_attributes => [:image])
end
来源:https://stackoverflow.com/questions/32441057/rails-paperclip-update-edit-multiple-images