CodexBloom - Programming Q&A Platform

ActiveStorage file uploads scenarios in Rails 7 with custom validators

πŸ‘€ Views: 26 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-10
ruby rails activestorage Ruby

Does anyone know how to I keep running into I'm confused about I've been researching this but I've been researching this but I'm attempting to set up I tried several approaches but none seem to work... I've been banging my head against this for hours. I'm working with an scenario when trying to upload files using ActiveStorage in my Rails 7 application. I've implemented a custom validator to ensure that uploaded files are of a certain type and size, but I'm running into unexpected behavior. When I attempt to save the model with the uploaded file, it fails silently without raising any validation errors, and the file does not get uploaded. Here is the code for my model: ```ruby class User < ApplicationRecord has_one_attached :avatar validate :avatar_format_and_size private def avatar_format_and_size if avatar.attached? unless avatar.content_type.in?(%('image/jpeg image/png')) errors.add(:avatar, 'must be a JPEG or PNG') if avatar.byte_size > 1.megabyte errors.add(:avatar, 'size must be less than 1MB') end end end end ``` I’ve checked that the avatar is actually being attached, but the validation seems to skip over it without adding any errors to `errors.full_messages`. I have also tried using `valid?` to check the validation before saving, but it still does not indicate any errors. Here’s how I’m trying to create a new user: ```ruby user = User.new(name: 'John Doe') user.avatar.attach(params[:user][:avatar]) if user.save puts 'User created successfully!' else puts user.errors.full_messages end ``` However, the output shows that the user is created successfully, and no errors are displayed concerning the avatar validation. I've tried adding `byebug` to debug and stepped through the code, but it seems like the validation method isn't being invoked as expected. Is there something I'm missing in terms of how ActiveStorage interacts with validations in Rails 7? Any advice would be greatly appreciated. My development environment is Ubuntu. My development environment is Linux. Thanks for taking the time to read this! I'm coming from a different tech stack and learning Ruby. Any examples would be super helpful. This is for a service running on Windows 11. I'd love to hear your thoughts on this. For context: I'm using Ruby on Debian. What am I doing wrong? I'm open to any suggestions.