That Postgres vs MySQL thread made me decide to get to know my DB (Postgres) a lot better. One of the things that I don''t use in any of my apps, but I''m sure is a good idea, is foreign key constraints. In all of my models that belong_to something else, I have a custom validate method which makes sure that the parent exists before saving. If it doesn''t, I add an error. That seems like a nice safeguard, but not the right way of doing it. To actually maintain referential integrity, you''d have foreign key constraints in the DB. So it''s no big deal to use fks AND do some validation in the model. But then we violated DRY...and in reality there''s no reason why Rails shouldn''t be able to parse foreign key violations from the DB. Maybe there is, maybe there isn''t, I don''t know. So really what I''d like to know is the best way to deal with business logic where you need to maintain referential integrity. Put it in the DB and add another layer in your rails app? Or is there some way for the rails app to infer it from the DB? FWIW, this has probably been discussed numerous times...but I think the gmane search is broken or something. No results even came up when I searched for ''ruby'' on the list. Of course we don''t talk about Ruby a whole lot here... Pat
Cynthia Kiser
2005-Aug-08 03:07 UTC
Re: Deal with foreign key constraints in app and/or db?
Quoting Pat Maddox <pergesu-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>:> So really what I''d like to know is the best way to deal with business > logic where you need to maintain referential integrity. Put it in the > DB and add another layer in your rails app? Or is there some way for > the rails app to infer it from the DB?The right way to do it is definitely to put foreign key constraints in the database. And it would be great if rails could inspect the database and generate the has_many or other attributes for the resulting classes. Problem with that is that you will end up writing custom code for each database that pulls out this information. That is, assuming that each database has an easy (I''m not talking about parsing the table you get from MySQL''s ''describe table'') way to query table structure/relationship information from each supported database. -- Cynthia Kiser