Active Storage in Rails 8.1 has no attachment validators; how would you reject an avatar over 5 MB or a non-PDF contract?
answer
- custom validate method in the model
- blob.byte_size against 5.megabytes
- content_type sniffed by Marcel
- direct uploads: bytes already stored
- unattached blobs need a sweep
basics
~20 sWrite a custom validate method that checks attachment.attached?, blob.byte_size and content_type and adds errors. The content type is sniffed from the bytes when the file is attached, and direct-uploaded files are already stored, so rejected ones need cleanup.
solid answer
~40 sRails 8.1 ships no size or content-type validator for attachments, so you write a `validate` method: return unless `avatar.attached?`, then add errors when `avatar.blob.byte_size > 5.megabytes` or `avatar.content_type` is not in an allow-list, and for a contract require `signed_pdf.content_type == "application/pdf"`. The values are trustworthy enough because Active Storage computes `byte_size` from the uploaded IO and identifies `content_type` from the file's first bytes with Marcel, using the browser's type only as a hint. With form uploads a failed validation uploads nothing, since the upload runs after commit. With direct uploads the bytes are already in storage and `byte_size` is the client's declared size, which an S3 upload URL is signed to enforce, so a rejected blob lingers until an `ActiveStorage::Blob.unattached` sweep purges it. The file field's `accept:` attribute is only a browser hint.
code
ruby · 16 linesclass Contract < ApplicationRecord
has_one_attached :signed_pdf, dependent: false
validate :signed_pdf_is_a_pdf
private
def signed_pdf_is_a_pdf
if !signed_pdf.attached?
errors.add(:signed_pdf, :blank)
elsif signed_pdf.content_type != "application/pdf"
errors.add(:signed_pdf, "must be a PDF")
elsif signed_pdf.blob.byte_size > 20.megabytes
errors.add(:signed_pdf, "must be 20 MB or smaller")
end
end
endgo deeper
Recall that Rails has no built-in attachment validators and that a custom validate method checks attached?, byte_size and content_type.
Explain where byte_size and content_type come from (server measurement, Marcel identification), why accept: is only a hint, and what a failed save leaves behind for form versus direct uploads.
Design the full defence: early refusal in a custom direct-upload endpoint, model validation as the authority, cleanup of rejected blobs, and post-commit checks for dimensions or scanning.
Decide which file checks belong in the request, which in background jobs, and which at the storage edge, balancing user feedback, cost and safety.
## Nothing built in, by design Active Storage gives you attachments, variants and services, but no validator for content type or file size; a Rails 8.1 model that needs limits enforces them itself (community gems exist, but they are not part of Rails). The good news is that every value you need is already on the blob by the time validations run. ```ruby class Freelancer < ApplicationRecord AVATAR_TYPES = %w[image/png image/jpeg image/webp].freeze has_one_attached :avatar validate :acceptable_avatar private def acceptable_avatar return unless avatar.attached? errors.add(:avatar, "must be 5 MB or smaller") if avatar.blob.byte_size > 5.megabytes errors.add(:avatar, "must be a PNG, JPEG or WebP") unless avatar.content_type.in?(AVATAR_TYPES) end end ``` A `Contract` with `has_one_attached :signed_pdf` follows the same pattern with `signed_pdf.content_type == "application/pdf"`, and a presence rule (`errors.add(:signed_pdf, :blank) unless signed_pdf.attached?`) when a contract cannot exist without its document. ## Where the checked values come from When an uploaded file is assigned, Active Storage builds a new blob from it before validations run: - **`byte_size`** is the IO's size, measured on the server. - **`checksum`** is a Base64 MD5 computed over the IO in chunks. - **`content_type`** is identified with the Marcel library from the file's leading bytes, with the filename and the browser-declared type as hints. A `.pdf` name on a PNG does not make it a PDF. Passing `identify: false` together with an explicit `content_type:` to `attach(io: ...)` skips this. For a **direct upload**, the blob was created earlier from the browser's declared filename, size, type and checksum. When the form's `signed_id` is assigned, Active Storage downloads the first 4 KB of the stored object and identifies the type again, so the content-type check still sees the real bytes. The `byte_size` is the declared one; the S3 service signs the upload URL with that content length and MD5, so the stored object has to match it. ## What a failed validation leaves behind | Path | Bytes in storage when validation fails? | Blob row? | Cleanup | |---|---|---|---| | Form upload through Rails | no, upload runs in `after_commit` | not saved | none | | `attach` on a persisted record | no; `attach` returns `nil` | not saved | none | | Direct upload | yes | yes, unattached | purge it, or sweep `ActiveStorage::Blob.unattached` | Two practical consequences: 1. On the form-upload path the user must choose the file again after a validation error; there is nothing to keep. 2. On the direct-upload path, either purge the rejected blob in the controller when the save fails or schedule a recurring task that runs `ActiveStorage::Blob.unattached.where(created_at: ..2.days.ago).find_each(&:purge_later)`. ## Layers that come before the model Model validation is the authoritative check, but not the only one worth having: - The file field's `accept:` attribute (`accept: "image/png,image/jpeg,image/webp"`) filters the picker; it is a hint the client may ignore. - A custom direct-uploads controller can refuse to create blobs over a size or outside a type list before any bytes move, because it sees the declared `byte_size` and `content_type` in its parameters. - Request-body limits at the proxy or app server stop absurd form uploads before Rails parses them; that belongs to the multipart-parsing layer, not Active Storage. ## Checks that interact with variants and analysis - Validate types you can actually process: a type outside `variable_content_types` makes `variant` raise `ActiveStorage::InvariableError` later, which is a worse failure than a validation message. - Image dimensions (`metadata[:width]`, `metadata[:height]`) are filled by the analysis job **after** the attachment commits, so they are not available to a validation on the same save. A minimum-resolution rule needs a job that inspects the analyzed blob and flags the record afterwards, or a check that opens the file with `blob.open` and reads it, at the cost of doing that work inside the request. - For multi-file fields, iterate `portfolio_images.blobs` (or `portfolio_images.each`) and also cap the count: `errors.add(:portfolio_images, "too many") if portfolio_images.size > 12`.
- Can you validate an image's pixel dimensions in the same save?Not from `metadata`: width and height are written by the analysis job that `analyze_later` enqueues after the attachment commits. You either check dimensions afterwards in a job and flag or reject the record there, or open the file during validation with `blob.open` and read its size with an image library, paying that cost inside the request.
- A user renames malware.exe to cv.pdf and uploads it. What does content_type report?Active Storage identifies the type from the leading bytes with Marcel, using the filename and declared type only as hints, so the blob's `content_type` reflects the executable's signature rather than `application/pdf`, and a PDF-only validation rejects it. Identification is not malware scanning; scanning still belongs in a separate pipeline.
- Active Storage rejects files above a built-in maximum size, so models need no size check
- content_type is just the type the browser declared, so it cannot be relied on
- A failed validation on a direct upload means the file never reached storage
- The accept: option on the file field is enough to enforce allowed types
- Image width and height are available in blob metadata during the first save's validations