Rails signed_id and sgid

Edit
equivalent Web Development
Public
Rails

signed_id = ActiveStorage::Blob.last.signed_id # no purpose
ActiveStorage::Blob.find_signed! signed_id
 #<ActiveStorage::Blob:0x00007f16792fc088 id: 3479>

signed_id = ActiveStorage::Blob.last.signed_id(purpose: :attachment_delete)
ActiveStorage::Blob.find_signed! signed_id,  purpose: :attachment_delete
#  #<ActiveStorage::Blob:0x00007f16799ccbd8 id: 3479>

signed_id = ActiveStorage::Blob.last.signed_id expires_in: 15.minutes, purpose: :foo
ActiveStorage::Blob.find_signed! signed_id # => ERROR, since the purpose does not match  # mismatched purpose (ActiveSupport::MessageVerifier::InvalidSignature)


ActiveStorage::Blob.find_signed! signed_id, purpose: :foo
#  #<ActiveStorage::Blob:0x00007f16799ccbd8 id: 3479>

travel 16.minutes
ActiveStorage::Blob.find_signed! signed_id, purpose: :foo
# error as it expired

sgid is different than signed_id !



a = ActiveStorage::Blob.last
sgid = a.to_sgid_param
ActiveStorage::Blob.find_signed!(sgid)
# ActiveSupport::MessageVerifier::InvalidSignature: mismatched digest (ActiveSupport::MessageVerifier::InvalidSignature)

GlobalID::Locator.locate_signed(sgid)  # returns object
#  => #<ActiveStorage::Blob:0x000000014e019100 id: 658300,  key: "pvh8pt0de0n1hcvklo3shjx9rwme",



signed_id
  • Used to securely reference records by ID without exposing raw IDs
 
sgid
 (Signed Global ID)


Controller 


class AttachmentsController < ApplicationController
  def destroy
    authorize @attachment.record

    @attachment.destroy
    respond_to do |format|
      format.turbo_stream { render :destroy }
    end
  end

  private

  def set_attachment
    @attachment = ActiveStorage::Blob.find_signed!(params[:id], purpose: :delete).attachments.first
  end
end

//app/views/attachments/destroy.turbo_stream.slim
= turbo_stream.remove dom_id(@attachment)

- attachment = User.avatar
= button_to "Destroy", attachment_path(attachment.signed_id(purpose: :delete)