All built in rails validators have access to the interpolations: model, attribute and value. Some validators such as length have access to the count interpolations. These can be used as follows:
1 2 3 4 5 6
If a user tries to create a username that is 26 characters they would get the message “Username is too large. Expected Username to be of length 25 but was 26” (note that attribute gets capitalized). This also works when the message is defined from a config/local/*.yml file.
When we write our own validators, it would be nice if we could define our own interpolations. Assume that we are writing a blog and need to validate that there are no duplicate tags passed. If there are duplicate tags, we should display which tags are duplicates. We can wip up a custom validator as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
The important part here is that when we call object.errors.add, we pass the symbol :duplicates_in_list (it has to be a symbol, else rails will just print out the message interpreted literally with no iterpolations, this also allows other developers to make custom translators using :duplicates_in_list as the key) followed by the option hash with keys :message and :duplicates. The :duplicates key is what essentially holds the custom interpolation. In this case we just pass the array of duplicates and join them with a comma. If we defined the following model:
1 2 3
1 2 3
we should see the message “Tags has duplicates: ruby”.