سؤال

I want to do some processing on an image the first time it's uploaded. The model can be updated without updating the image and I want to avoid extra processing in those situations. How can I write a check to only process the image if the image is new, like being replaced?

Something like:

def update
  @model = Model.find(params[:id])
  @model.process_image if @model.image_is_different_from_existing?
  ...
end
هل كانت مفيدة؟

المحلول 2

I've written a solution that looks for relevant params in the update or create method.

Something like this:

user.rb

def attachments
  %w(banner footer logo)
end

users_controller.rb

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(' ')

نصائح أخرى

There's one way if the photos you are uploading have unique name, Let's say paperclip attribute name is image, paperclip creates a column named image_file_name, before saving you can check whether the image file name present in your database matches with the name of image file you are uploading or not. I've implemented something like this, below is the snippet

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

THis might not be the perfect solution but it may be helpful to you

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top