How to add validation only to an associated table in active record

64 views Asked by At

I have an address table in rails:

class Address < ApplicationRecord
  validates :street, :city
            presence: { allow_blank: false }
end

the table is associated with several tables and I added validation to prevent street and city from being null or "", but I wanted this validation to only run on the associated table user

class User < ApplicationRecord
  belongs_to :address
  validates_associated :address
end

User has a belongs_to for address, and would not like to put a belongs_to inside the address. How do I make address validations only work when the table is user?

1

There are 1 answers

0
spickermann On

When you only want to validate the presence of street and city when there is a user or at least one user associated with the address then I would add a if condition to the validate definition, like this:

class Address < ApplicationRecord
  has_many :users

  validates :street, :city
            presence: { allow_blank: false },
            if: Proc.new { |a| a.users.present? }
end

class User < ApplicationRecord
  belongs_to :address

  validates_associated :address
end