How can i use Rails' update_attributes with a file upload?
My update method of a Product controller is defined as follows:
def update
@product = Product.find(params[:id])
if params[:product][:image_path]
# Check if this product already has an image
File.delete(@product.full_image_path) if File.exist?(@product.full_image_path)
# Upload the new image
uploaded_img = params[:product][:image]
@product.image_path = Time.now.to_i.to_s + File.extname(uploaded_img.original_filename)
File.open(@product.ful开发者_JAVA技巧l_image_path, 'w') do |file|
file.write(uploaded_img.read)
end
end
@product.name = params[:product][:name]
@product.description = params[:product][:description]
respond_to do |format|
if @product.errors.count == 0
format.html { redirect_to products_path, :notice => t(:product_updated) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @product.errors, :status => :unprocessable_entity }
end
end
end
This simply deletes the old image if already present, and uploads the new one. It also updates the Product attributes
How can I use @product.update_attributes(params[:product])
to avoid updating name and description attributes as I've done here?
If I do @product.update_attributes(params[:product])
I get an error because the params hash contains a value named "image" which is not an attribute of the object.
Thanks in advance
You could create an attribute setter for the image in the Product model called image=
:
def image=(uploaded_img)
# Check if this product already has an image
File.delete(full_image_path) if File.exist?(full_image_path)
# Upload the new image
image_path = Time.now.to_i.to_s + File.extname(uploaded_img.original_filename)
File.open(full_image_path, 'w') do |file|
file.write(uploaded_img.read)
end
end
After that, remove the rest of the code in the controller and use @product.update_attributes(params[:product]). I didn't tried it but I think it should work.
Do you know that you have some gems that allow to manage easily file upload like https://github.com/jnicklas/carrierwave or https://github.com/thoughtbot/paperclip
You should try to refactor your controller a bit, a controller should not be running any other tasks other than directing the traffic of your models and views. Try to move all your file operations to a separate helper.
精彩评论