Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get content type from an ActiveStorage attachment?

I'm creating a view that features a video stored via ActiveStorage. Currently I'm displaying the video like this:

%video{ controls: true, preload:"metadata" }
    %source{ src: rails_blob_path(@video.source), type: "TODO: Content Type" }

I'd like to find a way to get the content type from the attachment. I've found that I can get to it by using @video.source.attachment.blob.content_typebut that seems so clunky. Is there another simpler way to go about it that resembles video.source.content_type? Unfortunately using the video_tag helper is not a viable solution for me.

like image 466
CaTs Avatar asked Dec 08 '22 12:12

CaTs


2 Answers

Yes, there is a shorter solution: @video.source_blob.content_type.

I recommend you to look at the source code of ActiveStorage, there you can see all the available methods and possibilities that are not always well documented.

like image 71
Pere Joan Martorell Avatar answered Dec 11 '22 09:12

Pere Joan Martorell


You can access content type directly from the attachment , there is not need to call it in thet blob , just do : @video.content_type

class ActiveStorage::Attachment < ActiveRecord::Base
  self.table_name = "active_storage_attachments"

  belongs_to :record, polymorphic: true, touch: true
  belongs_to :blob, class_name: "ActiveStorage::Blob"

  delegate_missing_to :blob #This line allow you to call all the blob methods from attachmen
like image 31
Guzman90 Avatar answered Dec 11 '22 09:12

Guzman90