I need validate that user's email contains the value of it's association:
class Company << ApplicationRecord
validates :name, presence: true
has_many :users
end
class User << ApplicationRecord
belongs_to :company
validate :email, presence: true
end
I need that before an user is saved, its email contents its company's name, for example.
if company's name is: fedex
, the user's email has to be: example@fedex.com
I am using Rails 5.0
Update:
As mrlew said, I write the validator as methods, but besides this I wrote it at app/validator
as follows:
#User model
class User << ApplicationRecord
belongs_to :company
validate :email, presence: true
validates_with UserEmailValidator
end
#Validator
# app/validator/user_email_validator.rb
class UserEmailValidator < ActiveModel::Validator
def validate(record)
unless record.email =~ /\A[\w+\-.]+@#{record.company.name}\z/i
record.errors[:email] << "invalid email"
end
end
end