Rails API Only项目中如何获取ActiveStorage的thumb变体URL?
获取Rails Active Storage缩略图(Thumb)的URL
你只需要基于现有代码新增一个生成变体URL的方法即可,无需额外安装gem:
class CloudOperator < ApplicationRecord has_one_attached :op_logo do |attachable| attachable.variant :thumb, resize_to_limit: [100, 100] end def op_logo_url Rails.application.routes.url_helpers.url_for(op_logo) if op_logo.attached? end # 新增缩略图URL生成方法 def op_logo_thumb_url Rails.application.routes.url_helpers.url_for(op_logo.variant(:thumb)) if op_logo.attached? end end
说明:
- Active Storage的
variant(:thumb)会调用你预先定义的缩略图规格,自动生成对应的处理后图片 url_for方法支持直接处理ActiveStorage::Variant实例,生成变体的访问URL- 变体首次被访问时会完成生成并存储,后续访问将直接返回缓存好的URL
测试时在终端执行:
CloudOperator.last.op_logo_thumb_url
即可得到类似格式的缩略图URL:
"http://localhost:3001/rails/active_storage/variants/eyJfcmFpbiOnsibWVzc2FnZSI6IkJBaHBDdz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--d38ae8737261881a9cf099fdb2de584a367641/2chDe_kw.jpg?variant=thumb"
内容的提问来源于stack exchange,提问作者Gourav
相关产品推荐
相关产品推荐

