如何从 Carrierwave 中的 ID 和名称中查找 URL



我有模型消息,并附加文件

class Message
    has_one :attach_file
end
class AttachFile
    mount_uploader :path, FileUploader
end
class FileUploader
    def store_dir
        "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
    end
end

我有带有附加文件的控制器列表消息。

class Controller
     def index
         message = Message.join(:attach_file).select('messages.*, attach_files.*')
         render :json => message
     end
end

我尝试了很多方法来检索附加文件 url,它适用于公共存储桶,因为我从存储桶名称、id、名称附加文件中设置了 url。如果是私有公共,则需要访问密钥和签名,过期。是否有任何运营商波的方法可以找到附加文件网址

你在这里有两个问题:

  1. 如果您以这种方式使用select则无法访问相关模型上的CarrierWave方法。 一般来说,select用例很少;您可能不应该使用它。

  2. render json会忽略关联,除非您告诉它include关联(或者您已经覆盖了模型的as_json,或者您正在使用自定义序列化程序等......

一个额外的半问题是,join并不是你在这里真正想要的。避免 N + 1 查询的惯用方法是 includes

def index
  messages = Message.includes(:attach_file)
  render json: messages, include: :attach_file 
end

include: :attach_file更好的是使用像active_model_serializers这样的工具让视图层处理您的 json 序列化,但这个答案已经足够长了。

尝试:

message = Message.find params[:id]
file_url = message.attach_file.path.url

最新更新