Reputation: 19102
I'm coming from a background where the DB schema is defined as completely as possible, e.g. field lengths, not null, default values, complex referential integrity, etc. With Rails, I have to do all of that in the model to get smart validations. So do I duplicate everything in the database definition as well?
For example, if email is a required field, do I add validates :email, :presence => true
to the model AND :null => false
to the migration?
What about strings? If I have :length => { :maximum => 50 }
in the model, do I also want :limit => 50
in the migration?
Do I add foreign keys to the database to enforce referential integrity?
Or is the "Rails way" to do as much as possible in the model and leave the database as a "dumb" persistence engine?
Upvotes: 4
Views: 307
Reputation: 2230
Definately add :null => false. otherwise your DBA might hurt you. Your Rails app isn't the only thing that touches the DB.
max length gives you a gain DB memory. definitely set the max length but be sure to add the rails validations. If not you might get wierd app errors.
foreign keys are good but less used in rails apps
Upvotes: 2
Reputation: 160321
The standard "Rails Way" is to keep the constraints in the Ruby code.
I rarely have the luxury of having only Rails (or even just Ruby) touching the DB... And to be honest, even just people mucking around directly on the DB can cause problems... so I tend to use DB constraints as well, because I'm not sure data can ever be too-well groomed.
Upvotes: 1
Reputation: 10567
Normally the best practices are to leave as much logic out of the DB as possible. Adding nullable validation to your migrations doesn't really hurt or help from that aspect of keeping logic out. If you are using model validation then most of your app should travel through that anyways. It's a wash in my mind.
Where you can go overboard is other types of constraints. Some DBs support all kinds of crazy constraints that work better as validators - validators are easier to test and run those tests in an automated fashion.
If you have a number of pieces touching the DB and they aren't all ruby, then writing an SOA layer to do all the validation and such in code is often useful. Again, it's easier to test code than logic in the DB.
Upvotes: 0