ActiveStorage-获取模型中的变体URL

时间:2019-01-10 12:25:58

标签: ruby-on-rails rails-activestorage

我正在将Rails应用程序从使用PaperClip迁移到ActiveStorage。

在我的一个模型中,我有以下方法(使用回形针):

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

在控制器中,我有:

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

现在,我正在使用ActiveStorage,如何从thumb_url方法获取附件的缩略图网址?

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

不起作用Rails.application.routes.url_helpers.rails_blob_path(attachment.variant(resize: '200x200'), only_path: true)这将引发错误:NoMethodError (undefined method 'signed_id' for #<ActiveStorage::Variant:0x00007fac1960eab0>)

我该如何实现?

2 个答案:

答案 0 :(得分:2)

找到了!

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

this answer找到。

答案 1 :(得分:0)

attachment.variant(调整大小:“ 200x200”)。service.url对我有用。使用S3时,它会为您提供外部URL,而不是您应用程序的内部链接。