In a Rails model, if I have a field that is for proper names, what is the best practice way to ensure they are uniformly capitalized despite potentially lazy input from users?
IE let’s say the model is Contact and the field is Name. No matter what the user inputs I want the words to be capitalized, ie the model would tranform the following input to the following output:
john doe -> John Doe
j doe -> J Doe
John doe -> John Doe
john doe jr -> John Doe Jr
So, do you create a before_save callback and tranform the field with a regex, or do you create some kind of validation, or something different? I’d very much appreciate answers with an emphasis on the rationale, of why you would do it one way or another, because that’s what I’m most stuck on.
The method you want is
titleize. Thecapitalizemethod only does the first character in the entire string so"john doe".capitalize #=> "John doe","john doe".titleize #=> "John Doe".As for how to implement it, you could go with a
before_save, but I like to do these type of simple preparations of single attributes with pseudo-attributes. Basically, you define awritermethod for an attribute that will hide the default one created byActiveRecord. You’ll still be able to access the attribute using thewrite_attributemethod (docs). Doing it this way will ensure that the attribute is set properly as soon as you assign it, meaning that even before you save it, you can be sure your object is in a valid state: