Ruby on rails 如果我';我正在上传一个新文件?
我想在第一次上传图像时对其进行一些处理。模型可以在不更新图像的情况下进行更新,我希望在这些情况下避免额外的处理。如果图像是新的(如被替换),我如何写一张支票以仅处理该图像 比如:Ruby on rails 如果我';我正在上传一个新文件?,ruby-on-rails,ruby-on-rails-3,paperclip,Ruby On Rails,Ruby On Rails 3,Paperclip,我想在第一次上传图像时对其进行一些处理。模型可以在不更新图像的情况下进行更新,我希望在这些情况下避免额外的处理。如果图像是新的(如被替换),我如何写一张支票以仅处理该图像 比如: def update @model = Model.find(params[:id]) @model.process_image if @model.image_is_different_from_existing? ... end 如果您上传的照片具有唯一名称,有一种方法,比如说回形针属性名称为imag
def update
@model = Model.find(params[:id])
@model.process_image if @model.image_is_different_from_existing?
...
end
如果您上传的照片具有唯一名称,有一种方法,比如说回形针属性名称为
image
,回形针会创建一个名为image\u file\u name
的列,在保存之前,您可以检查数据库中的图像文件名是否与您上传的图像文件名匹配。我已经实现了类似的东西,下面是代码片段
product_images = product.product_attachments.pluck(:photo_file_name)
unless product_images.include?("name_of_the_image_i_am_uploading")
product.product_attachments.create!(:photo => File.open("/home/rajdeepb/Photo/#{data_array[1]}")) if all_images.include?("/home/rajdeepb/Photo/#{name_of_the_image_i_am_uploading}")
end
这可能不是一个完美的解决方案,但可能对您有所帮助我已经编写了一个解决方案,在
更新
或创建
方法中查找相关参数
大概是这样的:
user.rb
def attachments
%w(banner footer logo)
end
def new_resources?
attaching = []
@user.attachments.each do |a|
attaching << a if params[:user][a].present?
end
return true unless attaching.empty?
end
def attaching
[]
end
def update
...
if @user.request_necessary? && new_resources?
action_response << "Server updated: new #{attaching} uploaded."
redirect_to users_path, notice: action_response.join(' ')
用户\u控制器.rb
def attachments
%w(banner footer logo)
end
def new_resources?
attaching = []
@user.attachments.each do |a|
attaching << a if params[:user][a].present?
end
return true unless attaching.empty?
end
def attaching
[]
end
def update
...
if @user.request_necessary? && new_resources?
action_response << "Server updated: new #{attaching} uploaded."
redirect_to users_path, notice: action_response.join(' ')
def新资源?
附加=[]
@user.attachments.each do|a|
谢谢你的建议。处理的一部分包括重命名似乎有问题的文件,除非我可以对照数据库中存储的内容检查发布前的名称?但感觉应该有更好的方法。特别是,如果名字匹配,那就失败了。