mercredi 10 novembre 2021

Attachments adding duplicates in active storage

I have a Message model which has

 has_many_attached :attachments

My functions:

  def update_attachment
        remaining_attachment_ids = attachment_params[:existing]
        if message.attachments.attached? && errors.empty?
          message.attachments.where.not(id: remaining_attachment_ids).purge
          message.reload
          puts "AFTER DELETE"
          puts message.attachments.count
        end
        message.reload

        attach_new_files
      end

      def attach_new_files
        if attachment_params[:new]
          puts attachment_params[:new].map { |attachment| attachment["blob_signed_id"]}
          message.attachments.attach(attachment_params[:new].map { |attachment| attachment["blob_signed_id"] })
          message.reload
          puts "AFTER UPDATE"
          puts message.attachments.count
        end
      end

I'm trying to purge some and then add new attachments in a two step process. First I purge the attachments and the message.attachments.count is getting printed correctly.

However when I do attach_new_files, After the attachments I'm getting an extra count. For example, I have only 2 items in attachment_params[:new] array. When I print the count after attaching, It's showing 3. I have supplied only 2 blob_signed_ids to attach. What might be the issue here?

Aucun commentaire:

Enregistrer un commentaire