ActiveRecord enums are really handy but they can be equally evil if not used properly.

Recently we encountered a strange situation where a developer added a simple has_one-belongs_to relationship between two of the models - Investor has one BankAccount. And it did not work!

BankAccount.first.investor was working but Investor.first.bank_account was returning nil even though the bank_account existed for that investor.

I went in to debug.

  • Foreign key bank_account_id - check

  • spellings everywhere - check

  • Try relationship in console - fails

Why on earth was a simple relationship like this failing? We have used this hundreds of times! It should just work! After spending a good 20mins into this, found out that there was an enum defined on Investor with the name bank_account. Bam!

ActiveRecord enums are very useful in the way they map domain level states to integers in database (or even enums in case of postgres), but what they do is monkey-patch activerecord with various methods corresponding to the enums. And in this case the enum method #bank_account took priority over the relation method with the same name.


Use enums carefully and sparingly keeping in mind the plethora of methods it defines on your model.