Search code examples
ruby-on-railsrails-activestorage

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

How do i access avatar(rails_blob_url) from Userspublication i have this following query?

This is what i have tried

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)

Solution

  • Thank you for the help guys (specially @arieljuod) i figured out the answer it was pretty simple :

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

    Here object is of Userspublication!

    (The guy who down voted this question if you cant answer and can't even bother to help in understanding whats wrong with it "suck it"!!)