Scott Fister
Scott Fister

Reputation: 1283

Rails validate model with attribute

I need to do a custom validation that checks if the attribute being updated is less than another attribute on that record. I tried doing this:

validates :team_size, :numericality => { :greater_than_or_equal_to => self.users.count }

But it comes back with the error:

NoMethodError (undefined method `users' for #<Class:0x007fcda9a548e8>):

I also tried doing a before_save hook with a method like this:

  def validate_team_size
    if self.team_size < self.users.count
      errors[:base] << "Custom message."
    end
  end

But it just ignores it - I'm assuming because the team_size attribute hasn't been updated yet so I'm checking the old value. Also tried using after_save which is just before it commits but no luck either.

Upvotes: 1

Views: 305

Answers (1)

Mark Swardstrom
Mark Swardstrom

Reputation: 18130

What you had was close. Try something like this..

validate :team_size_less_than_users_count

def team_size_less_than_users_count
  if team_size < users.count
    errors[:base] << "Custom message."
  end
end

To access instance variables, you do it like this...

validates_numericality_of :team_size, :greater_than_or_equal_to => Proc.new {|c| c.users.count }, :message => 'Custom message'

This syntax works as well

validates :team_size, :numericality => { :greater_than_or_equal_to => Proc.new {|c| c.users.count }, :message => 'Custom message'}

Upvotes: 2

Related Questions