How to: Detect if validating inside model

In a model I needed to modify a getter to append a string if a certain attribute evaluated to true. This works great, until I needed to detect the uniqueness of the attribute against a column in the DB through the :uniqueness validator.

The problem

1
2
3
4
5
6
7
8
9
  def label
  new_value = read_attribute(:label)
 
  if self.something == true
    new_label += 'Str'
  end
 
  new_label
end

When validating against the label’s uniqueness the validator will read the label attribute from my custom getter, thus, if a record in the DB has a label of ‘Test’, and our new record has a label of ‘Test’ and self.something evaluates to true, the validator will get ‘TestStr’ from the getter and compare the custom value against the DB. Based on this setup, no match would be found.

Solution

An extremely simple solution to this problem is to detect if validation is occurring, to do this you can simply check if the objects validation_context is set. For example:

1
2
3
4
5
6
7
8
9
def label
  new_value = read_attribute(:label)
 
  if self.something == true && !self.validation_context
    new_label += 'Str'
  end
 
  new_label
end

You can also check which context is in used (:create, :update) if need be.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>