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 %>