Advanced Active Record Validations with Rails
Assigning Support Request Priority Based on Email Address
Suppose you added another column, named priority, to the Question model. This column will be used internally to identify requests coming from a particularly lucrative client as particularly urgent. By parsing the email address, you can identify the domain name, and flag it as being of high priority. Because you would only want to do so when the email address has been deemed valid, you should use the after_validation_on_create() method. The following code should do the trick:
class Question < ActiveRecord::Base def after_validation_on_create address = self.email.split('@') if address == "example.com" self.priority = 1 else self.priority = 0 end end end
In a real-world situation, chances are high you'll actually have several high-profile clients, and therefore might identify clients as of a certain priority within the Client model. In such a case, you could modify the above code to look to the appropriate client table and determine whether the support request is coming from a member of one of the high-profile clients. Nonetheless, the above example should give you ample indication of how to implement such a task.
Removing Attribute Names From Error Messages
Name can't be blank!
That works, but what if you wanted to use a somewhat more grammatically correct message, such as "Your first and last name are required."? Based on this default prefixing, the error message would look like this:
Name Your first and last name are required.
A reader posed this question to me a few days ago, and after a bit of research I've located a great solution. To remove these prefixes, just install the Custom Error Message plugin. Then, all you have to do is prefix your custom message with ^, like so:
validates_presence_of :name, :message=>"^Your first and last name are required."
Rails' Active Record implementation offers an unbelievable array of validation features that can go a very long way towards ensuring user input is provided exactly as you intend it to be. Hopefully, this two-article series helps you understand these sometimes cryptic features.
About the Author
W. Jason Gilmore is co-founder of IT Enlightenment. He's the author of several books, including the best-selling Beginning PHP and MySQL 5: Novice to Professional, Second Edition (Apress, 2006. 913pp.). Jason loves receiving email, so don't hesitate to write him at wjATwjgilmore.com.
Page 2 of 2