before_validation

before_validation(*args, &block)
Instance Public methods

Defines a callback that will get called right before validation happens.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Person
  include ActiveModel::Validations
  include ActiveModel::Validations::Callbacks
 
  attr_accessor :name
 
  validates_length_of :name, maximum: 6
 
  before_validation :remove_whitespaces
 
  private
 
  def remove_whitespaces
    name.strip!
  end
end
 
person = Person.new
person.name = '  bob  '
person.valid? # => true
person.name   # => "bob"
doc_ruby_on_rails
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.