Improving upon Rails' validates_inclusion_of

I’m fairly new to the Ruby language and the Ruby on Rails framework, but it worked nicely for quickly building my website BirdSite.

I was using validatesinclusionof fairly regularly to make sure the data in my models was valid. But then, watching the development log, I noticed extra SQL queries being made when I accessed my main model. It seems that validatesinclusionof was forcing the model to make queries to the related models even when I didn’t need data from them.

Some Googling led to a blog post that did the validation a different way. It worked well, until I added the code to a new model today and it broke. The code was translating the model field name into a string from which to call the model itself. But the code assumed that the model would be a single word. I added a change to strip the spaces out, and it worked again.

I contacted the company that hosts the blog and they confirmed that it was a problem, and they didn’t know of a nicer Ruby way to correct it short of dropping the spaces with search/replace. They updated their code.

I’m glad I could help out. It really works better than the standard validatesinclusionof.