Skip to content

Media Items

Dylan Fisher edited this page Feb 14, 2022 · 5 revisions

Points of Interest

Add points of interest to media items that allow background images to be positioned according to a central point on the image.

bin/rails generate migration AddPointOfInterestToMediaItems point_of_interest_x:float point_of_interest_y:float

# db/migrate/20190508182450_add_point_of_interest_to_media_items.rb

class AddPointOfInterestToMediaItems < ActiveRecord::Migration[6.0]
  def change
    add_column :media_items, :point_of_interest_x, :float, default: 50
    add_column :media_items, :point_of_interest_y, :float, default: 50
  end
end

Set the background image's style in your views

<%= content_tag :div, style: "background-image: #{@media_item.attachment.url(:medium)}; background-position: #{@media_item.point_of_interest_x}% #{@media_item.point_of_interest_y}%;" %>

Migrating media items between AWS S3 sources

If you find yourself in a situation where you've started developing an app using test S3 credentials (e.g. you were waiting on the client to get this info to you, but got started before the production AWS environment is set up), you may need to move Media Items that were uploaded to one location to the new location.

First, make sure you update your Rails credentials with the new, production S3 credentials. Take note of the original asset host (pointing to the development CloudFront domain), and update the original_host and new_host variables below.

# Swap with your original and new asset hosts.
original_host = 'https://my-development-host.cloudfront.net'
new_host = 'https://my-production-host.cloudfront.net'

MediaItem.find_each do |media_item|
  url = media_item.attachment_url
  url = url.sub(new_host, original_host)
  
  # Check to see if the file was already downloaded (e.g. you can run this script multiple times, but the file will only be uploaded to the new source once)
  begin
    file = Down.open(url)
  rescue Down::ClientError => e
    if error.response.code == '403'
      puts 'File no longer exists - this likely means this file was already processed.'
    else
      raise 'Down ClientError not rescued'
    end
  end

  media_item.attachment = file
  media_item.save!
end