Forum for Devs 1 discussion
Forum for Devs 1 discussion
Join community
Help Needed: Validation Issue in Ruby on Rails Model
Hi everyone, I'm facing a puzzling issue while working on my Ruby on Rails project, and I was hoping someone here might have some insights. Here’s the situation: Rails version: 6.1.7 Ruby version: 3.0.3 Problem Description: I'm trying to implement a custom validation for my User model to ensure that an email address is unique before saving to the database. However, the custom validation doesn’t seem to trigger, and duplicate emails are still being saved. What I've Tried: Checked the validate method syntax in the model. Verified that the database schema allows duplicate emails (intentionally removed the unique constraint for testing the validation). Looked at the server logs, but no errors related to the validation are showing up. Relevant Code: ruby Másolás Szerkesztés class User < ApplicationRecord validates :email, presence: true validate :email_must_be_unique private def email_must_be_unique if User.where(email: email).exists? errors.add(:email, 'has already been taken') end end end Error Message (if any): No error message, but duplicate emails are being saved without triggering the custom validation. Expected Behavior: When I try to save a User with an email that already exists, it should raise a validation error and not save the record. Actual Behavior: Records with duplicate emails are being saved, and the custom validation doesn’t seem to run. I've checked the Rails guides and other forums, but I can't figure out what I’m doing wrong. Does anyone have experience with this or know what might be causing the issue? Any advice or pointers would be greatly appreciated! Thanks in advance! 🙏 You can copy and paste this directly. If your issue is different, let me know, and I can adjust it!