How can I get content type from an ActiveStorage attachment?
Asked Answered
W

3

7

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.

Weese answered 6/6, 2019 at 3:0 Comment(3)
why don't you add a helper method on your model? def content_type; source.attachment.blob.content_type; end and then you do @video.content_type?Hectoliter
@Hectoliter Before I do that, I want to be sure my helper method isn't just reinventing an existing method.Weese
api.rubyonrails.org/classes/ActiveStorage/Blob.htmlMalawi
M
10

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.

Mythical answered 7/6, 2019 at 23:2 Comment(0)
H
7

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
Herzel answered 21/11, 2019 at 2:41 Comment(1)
Could you please provide a full answer including @video.content_typeRibwort
P
1

ActiveStorage uses Marcel to validate and get content types. An exhaustive list of everything is available here:

https://github.com/rails/marcel/blob/main/lib/marcel/tables.rb

Pippy answered 8/12, 2021 at 16:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.