Are there advantages to using foreign key constraints when working in an active record framework like ruby-on-rails?

StackOverflow https://stackoverflow.com/questions/3168995

문제

I'm moving back into full time web development after a 5 year hiatus. My previous experience (no active record or MVC) tells me to be very thorough with my database schema. Foreign key constraints, unique indexes, etc... can really help out when your writing spaghetti code.

Does the community still find these useful when working in an Active Record / MVC framework?

EDIT

My main concern is managing the constraints in two places; the model code and the db. This means duplicate work and it could lead to bugs. I.e. you have a unique constraint on some field in the database but the model does not know about it? I guess the reverse is true as well, you could just forget to put the constraint in the model then you would have duplicate data when you don't want it.

도움이 되었습니까?

해결책

It will work fine, however in cases you have to be careful of double click race condition bugs (as validates_uniqueness_of suffers from race conditions).

As far as the model is concerned it doesnt care, the logic in the database is separate to the logic in the Rails app.

다른 팁

If you don't use constraints, your database will accumulate cases of broken referential integrity and duplicates where there should be unique values, etc.

More to the point, if you do use constraints (and don't get in the habit of disabling them from time to time as some people do), you'll always have assurance that all your data conforms to your intended data model.

That's the value of database-enforced constraints: it's the only way you can be sure of your data, and you won't have to double-check that your framework (e.g. ActiveRecord) has worked correctly. You won't have to write SQL cleanup scripts to find spurious orphans and duplicates.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top