Want more GoRails?
GoRails is packed full with 688 lessons just like this one.
Sign up to get full access or log in to your account and sit back.
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.
Notes
Resources
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
Rails Concepts
0% Complete
1
Environment Variables
8m
2
Ruby Version Managers
4m
3
Rails Application Structure
14m
4
The Params Hash
15m
5
Sending Data Between Controllers And Views
5m
6
Querying Named Scopes Across Models with ActiveRecord::Relation#merge
4m
7
Understanding Semantic Versioning
9m
8
A Look Into Routing
9m
9
Forms With Multiple Submit Buttons
10m
10
Basic Authentication and RSS Feeds
13m
11
Pair Programming on Rails Scopes
1h 3m
12
Rails 5's ActionCable and Websockets Introduction
18m
13
Creating a Railsbyte
29m
14
Rails Counter Caches
21m
15
Atomic Updates And Performance with ActiveRecord Transactions
15m
16
Debugging: How to Interpret a Stacktrace
13m
17
Rails Application Templates
13m
18
Custom Rails Configuration Options
15m
19
ActiveRecord Default Scopes, Unscoped, and Unscope
12m
20
Mail Interceptors & Observers in Rails
7m
How to Build Custom ActiveRecord Validations
10m
22
Custom Route Constraints & Regex in Rails
5m
23
Building has_one from has_many Associations
9m
24
Serializing Attributes with Custom Coders
22m
25
ActiveSupport Concerns: Making A Duration Calculation Module
24m
26
The difference between Link_to vs Button_to in Ruby on Rails
14m
27
Understand Scope Returns
28m
28
How Rails.env works with EnvironmentInquirer & StringInquirer
12m
29
Powerful Rails Features You Might Not Know
42m
30
Enhancing the Rails Scaffold Generator with hook_for`
14m
31
ActionController Modules in Rails
3m