Tag Archives: Validation

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. Continue reading