mridula
mridula

Reputation: 3281

ActiveStorage - Get variant URL in model

I am in the process of migrating my Rails app from using PaperClip to ActiveStorage.

In one of my models, I had the following method (using paperclip):

class ECard < ActiveRecord
    def thumb_url
        self.attachment.url(:thumb)
    end
end

And in the controller I have:

def by_type
    @e_cards = ECard.where(type_id: params[:type_id]).as_json(:only => [:id, :name], :methods => [:thumb_url])
    respond_to do |format|
        format.json { render json: @e_cards }
    end   
end

Now, that I am using ActiveStorage, how to I get the thumbnail url of the attachment from the thumb_url method?

Works: Rails.application.routes.url_helpers.rails_blob_path(attachment, only_path: true)

Does not work: Rails.application.routes.url_helpers.rails_blob_path(attachment.variant(resize: '200x200'), only_path: true) This throws the error: NoMethodError (undefined method 'signed_id' for #<ActiveStorage::Variant:0x00007fac1960eab0>)

How do I achieve this?

Upvotes: 4

Views: 6196

Answers (2)

Juanin
Juanin

Reputation: 600

attachment.variant(resize: "200x200").service.url works for me. It give you the external url while working with S3 and not the internal link for your app.

Upvotes: -1

mridula
mridula

Reputation: 3281

Found it!

def thumb_url 
    Rails.application.routes.url_helpers.rails_representation_url(attachment.variant(resize: "200x200").processed, only_path: true)
end

Found from this answer.

Upvotes: 11

Related Questions