Dex
Dex

Reputation: 12749

Rails and Data Integrity

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?

Upvotes: 1

Views: 872

Answers (3)

Dex
Dex

Reputation: 12749

I've been keeping up with this and I've come up with a hybrid solution.

I think the default Rails polymorphism functionality is very well suited for rapid prototyping. But for a long term solution, I've implemented by own polymorphic association using an intermediary table (e.g. Commentable, Votable). I can't find the post, but Bill Karwin points this method out in several answers on this site.

I don't plan on sharding, but if I did, I think Rails' default solution would be a good one.

I wrote my own Mixins to emulate the default Rails polymorphism functionality. It was a little tricky with foreign keys added in, or when adding the relationship after the table has been populated, but things seem to operate smoothly still.

Finally, my project will eventually have multiple services running analytics on an undetermined backend, most likely Java. Referential integrity aside, having a standard relational model is best suited for my needs.

In Short, I think it does depend, but in 90% of cases, having DB level integrity is best.

Upvotes: 0

Omar Qureshi
Omar Qureshi

Reputation: 9093

There's always http://www.postgresql.org/docs/current/static/ddl-inherit.html

I never got round to it, but, was working (during a boring commute) on trying to make that work nicely with Rails.

Upvotes: 1

Ariejan
Ariejan

Reputation: 11069

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_of is 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.

Upvotes: 1

Related Questions