【发布时间】:2011-02-15 17:17:16
【问题描述】:
我的 Product 控制器的更新方法定义如下:
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.full_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
这只是删除已经存在的旧图像,然后上传新图像。它还会更新产品属性
我如何使用@product.update_attributes(params[:product]) 来避免像我在这里所做的那样更新名称和描述属性?
如果我这样做 @product.update_attributes(params[:product]) 我会收到错误,因为 params 哈希包含一个名为“image”的值,它不是对象的属性。
提前致谢
【问题讨论】:
标签: ruby-on-rails ruby model-view-controller