Your Teacher | Chris Oliver
Hi, I'm Chris. I'm the creator of GoRails, Hatchbox.io and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.
About This Episode
Custom ActiveRecord validations are easy to make and they're implemented exactly the same way as the built-in Rails validations. It's super handy to be able to add nice, clean validations that you can repeat throughout your apps.
Here's our example Resizable Image Validator that validates image content types that are uploaded. We can make sure we only accept image types that are resizable using this validator.
# app/validators/resizable_image_validator.rb class ResizableImageValidator < ActiveModel::EachValidator # Only allow resizable image formats # SVGs aren't allowed because they can contain XSS # def validate_each(record, attribute, value) return unless value.attached? if ActiveStorage.variable_content_types.exclude?(value.content_type) record.errors.add(attribute, :image_format_not_supported) end end end
# app/models/user.rb class User < ApplicationRecord has_one_attached :avatar validates :avatar, resizable_image: true end