ActiveStorage - 获取模型中的变体 URL

mri*_*ula 2 ruby-on-rails rails-activestorage

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

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

class ECard < ActiveRecord
    def thumb_url
        self.attachment.url(:thumb)
    end
end
Run Code Online (Sandbox Code Playgroud)

在控制器中,我有:

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
Run Code Online (Sandbox Code Playgroud)

现在,我正在使用 ActiveStorage,如何从thumb_url方法中获取附件的缩略图 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>)

我如何实现这一目标?

mri*_*ula 7

找到了!

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

这个答案中找到。

  • 这种“hack”是一种代码味道(它“很难”做到,因为 url 与视图更相关,不属于模型,而是属于您正在渲染的视图)。您可以使用 json 视图,而不是使用 `as_json`。`as_json` 在某些情况下很好,但感觉有时使用视图更干净。 (2认同)