Rails Validating Field vs Association

One really interesting thing I came across recently is validating a field vs association. I’ve always written something like this (assume this is a… Company model with a attribute called owner_id and a belongs_to association called owner):

validates_presence_of :owner_id

What’s better to write is:

validates_presence_of :owner 

This actually makes sure that your :owner_id actually maps to a real object in the database. So you can’t just set a random integer as owner_id and get away with it!

Sadly this has made testing a little bit harder. Tearing through FactoryGirl documentation again now!