Skip to content

Instantly share code, notes, and snippets.

@rubys
Created June 11, 2024 13:39
Show Gist options
  • Save rubys/20ea2562b9e7d23e3f01a6852f30d731 to your computer and use it in GitHub Desktop.
Save rubys/20ea2562b9e7d23e3f01a6852f30d731 to your computer and use it in GitHub Desktop.
Active Storage Demo - diffs
--- a/app/views/items/_item.html.erb
+++ b/app/views/items/_item.html.erb
@@ -6,7 +6,21 @@
<p class="my-5">
<strong class="block font-medium mb-1">Contents:</strong>
- <%= link_to item.contents.filename, item.contents if item.contents.attached? %>
+ <% if item.contents.attached? %>
+ <% if item.contents.content_type.start_with? 'image/' %>
+ <img src=<%= item.contents.url %> alt="<%= item.contents.filename %>">
+ <% elsif item.contents.content_type.start_with? 'audio/' %>
+ <audio controls>
+ <source src=<%= item.contents.url %> type=<%= item.contents.content_type %>>
+ </audio>
+ <% elsif item.contents.content_type.start_with? 'video/' %>
+ <video controls>
+ <source src=<%= item.contents.url %> type=<%= item.contents.content_type %>>
+ </audio>
+ <% else %>
+ <%= link_to item.contents.filename, item.contents %>
+ <% end %>
+ <% end %>
</p>
</div>
--- a/app/controllers/items_controller.rb
+++ b/app/controllers/items_controller.rb
@@ -1,5 +1,6 @@
class ItemsController < ApplicationController
before_action :set_item, only: %i[ show edit update destroy ]
+ include ActiveStorage::SetCurrent
# GET /items or /items.json
def index
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -7,5 +7,5 @@ Rails.application.routes.draw do
get "up" => "rails/health#show", as: :rails_health_check
# Defines the root path route ("/")
- # root "posts#index"
+ root "items#index"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment