如何从Userspublication获取附加到用户模型的化身的rails_blob_url?

时间:2019-05-12 20:32:52

标签: ruby-on-rails rails-activestorage

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)

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

谢谢您的帮助(特别是@arieljuod),我发现答案很简单:

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

这里的对象属于Userspublication!

(如果您无法回答,甚至不愿意帮助理解它的问题,那位投下了这个问题的人就会“吮吸它!”!)