I’m currently on the fence on how to implement my models. Right now I’m using polymorphic relationships, but it feels so wrong, though very convenient. I feel like I should be making use of database level integrity enforcement as an added layer of security.
Am I a grandpa for questioning the application layer? Please discuss.
I did find this post, but it is not Rails specific
Possible to do a MySQL foreign key to one of two possible tables?
It all depends.
If your application is the only one that access the database (e.g. there are no other tools writing to it), you can verify data integrity in your application code.
There are some things, however, that are still best done in the database.
validates_uniqueness_ofis a good example here. Two app instances may report a given value unique, but there may be a race condition. Having a unique index in your database here is good practice.I always handle integrity checking in my app code, using indices for uniqueness constraints. I don’t bother with foreign_key relations, I let ActiveRecord handle that.