willcodejavaforfood
willcodejavaforfood

Reputation: 44063

Dynamic form validation in Rails

I have a form which I want to validate. The validation is based on properties in a couple of other model objects, but the form itself does not correspond to a ActiveRecord model.

Would it be possible to use ActiveModel to achieve this?

class Person < ActiveModel
  has_one :shoe
  validates :name, :length => { :maximum => self.shoe.size }
end

I basically want to validate a form based on the properties of another model object. Is this possible in anyway?

Upvotes: 1

Views: 1246

Answers (1)

Viktor Tr&#243;n
Viktor Tr&#243;n

Reputation: 8884

class Person 
  include ActiveModel::Validations

  # has_one :shoe # This won't work

  validates :validates_name_length

  private
  def validates_name_length
    errors.add :name, 'too long' if name && name.length > shoe.size 
  end
end

Upvotes: 2

Related Questions