ruby on rails: duplicate images uploaded with each form submission
I'm uploading to Cloudinary from an external URL using this Ruby On Rails code:
class Item < ActiveRecord::Base
validates :picture_link, presence: true
before_save :get_cloudinary_url
def get_cloudinary_url
_ upload = Cloudinary::Uploader.upload(self.picture_link.to_s)_
_ self.secure_url = upload["secure_url"]_
_ self.public_id = upload["public_id"]_
This works well, but EVERY time the form is submitted, a duplicate image gets uploaded. Ideally I'd like to tell rails to only the get_cloudinary_url _function in the case that the _picture_link has been actually changed.
-
I tried adjusting the function to this
def get_cloudinary_url
#get from cloudinary the secure_url and add it to the item.
_ if self.changed?_
_ upload = Cloudinary::Uploader.upload(self.picture_link.to_s)_
_ self.secure_url = upload["secure_url"]_
_ self.public_id = upload["public_id"] _
_ end_
_ end_but still duplicate images are uploaded.
-
Can you please try the following and let me know if this helps? :
if self._picture_link__changed?
_ ...
_You might want to consider using our CarrierWave integration to simplify this process.
-
The
_changed?
method is a boolean. The.changes
method returns an array. See: http://api.rubyonrails.org/classes/ActiveModel/Dirty.htmlHowever, I'm glad it works for you now :)
Post is closed for comments.
Comments
4 comments