【问题标题】:How can i use Rails' update_attributes with a file upload?我如何在文件上传中使用 Rails 的 update_attributes?
【发布时间】: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


    【解决方案1】:

    您可以为 Product 模型中的图像创建一个属性设置器,名为 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
    

    之后,删除控制器中的其余代码并使用@product.update_attributes(params[:product])。 我没有尝试过,但我认为它应该可以工作。

    您知道您有一些可以轻松管理文件上传的 gem,例如 https://github.com/jnicklas/carrierwavehttps://github.com/thoughtbot/paperclip

    【讨论】:

    • 哇,我想我为我的上传选择了回形针宝石!它也构建了缩略图(这将是我开发的下一步)所以它是完美的!非常感谢!
    【解决方案2】:

    你应该尝试重构你的控制器,控制器不应该运行任何其他任务,除了指导你的模型和视图的流量。尝试将所有文​​件操作移至单独的帮助程序。

    【讨论】:

    • 这就是问题所在 - 他如何使用 update_attributes 来避免这种混乱。
    猜你喜欢
    • 1970-01-01
    • 2014-05-14
    • 2012-11-12
    • 2011-04-25
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    相关资源
    最近更新 更多