如何从 Userspublication 获取附加到 User Model 的头像的 rails_blob_url?

How to get rails_blob_url for the avatar attached to User Model from Userspublication?

class User < ApplicationRecord
  has_many :userspublications
  has_one_attached :avatar
end
class Userspublication < ApplicationRecord
  belongs_to :user
  has_one_attached :post
end

我如何从 Userspublication 访问头像 (rails_blob_url) 我有以下查询?

这是我试过的

Userspublication.joins(:user)
.joins("LEFT OUTER JOIN followers ON followers.user_id=users.id 
        Left Outer join active_storage_attachments 
        ON active_storage_attachments.record_id = users.id 
        AND active_storage_attachments.record_type = 'User' 
        AND active_storage_attachments.name = 'avatar'
        where followers.followeduser_id = 3 or users.id = 3").select("users.first_name,users.last_name,active_storage_attachments.record_type as 'avatar',userspublications.*").order(updated_at: :desc)

您可以从 active_storage_attachments table 中获取字段 blob_id,然后使用它来获取带有 blob = ActiveStorage::Blob.find(blob_id) 的 Blob。然后你可以调用 url_for(blob).

谢谢你们的帮助(特别是@arieljuod)我想出了答案很简单:

return rails_blob_path(object.user.avatar, only_path: true)

这里的对象是Userspublication!

(如果你不能回答这个问题,甚至懒得帮助理解它有什么问题,这个问题就会投反对票的人 "suck it"!!)