Skip to content

Instantly share code, notes, and snippets.

@stevepolitodesign
Last active December 19, 2021 11:20
Show Gist options
  • Save stevepolitodesign/fb783f22db2c3bd958cca52d5d4d512c to your computer and use it in GitHub Desktop.
Save stevepolitodesign/fb783f22db2c3bd958cca52d5d4d512c to your computer and use it in GitHub Desktop.
Validate Active Storage Attachements
class Webpage < ApplicationRecord
  has_one_attached :open_graph_image

  validate :open_graph_image_content_type
  validate :open_graph_image_size

  private

  def open_graph_image_content_type
    return if open_graph_image.content_type.nil?
    permitted_content_type = %w[JPEG PNG]
    content_type = open_graph_image.content_type.split("/").last.upcase
    if !permitted_content_type.include? content_type
      errors.add(:open_graph_image, "should be a an JPEG or PNG")
    end
  end

  def open_graph_image_size
    return if open_graph_image.byte_size.nil?
    if open_graph_image.byte_size > 2000000
      errors.add(:open_graph_image, "cannot be larger than 2MB")
    end
  end
end
<%= form_with model: @webpage do |form| %>
  <%= form.label :open_graph_image, class: "form-label" %>
  <!--  Use the accept attribute for client side validation -->
  <%= form.file_field :open_graph_image, accept: "image/png, image/jpeg" %>
  <%= form.submit "Share The Link", class: "btn btn-primary" %>  
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment