# Handling database table dependenciese

**URL:** <https://www.ruby-forum.com/t/handling-database-table-dependenciese/163217>\
**Category:** Rails\
**Created:** [March 18, 2009, 12:05pm UTC](https://www.ruby-forum.com/t/handling-database-table-dependenciese/163217 "2009-03-18T12:05:29Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![msmsms](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/34f0e0/32.png) [@msmsms](https://www.ruby-forum.com/u/msmsms)\
**Post date:** [March 18, 2009, 12:05pm UTC](https://www.ruby-forum.com/t/handling-database-table-dependenciese/163217/1 "2009-03-18T12:05:29Z")

</div>

Hey,

thanks for reading this post. How do you handle dependencies? A really  
simple example: I’ve got a table called “entity” and another table,  
let’s say, “entity\_type”. The entity types can be changed, of course,  
they also should be deletable, but only, if they are not used by some  
entities! How can I ensure this in Rails or directly in the DBMS  
(postgres)? Do I have to check it manually within a validate-method in  
the model?

---

<div class="post-metadata">

**Author:** ![msmsms](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/34f0e0/32.png) [@msmsms](https://www.ruby-forum.com/u/msmsms)\
**Post date:** [March 18, 2009, 5:06pm UTC](https://www.ruby-forum.com/t/handling-database-table-dependenciese/163217/2 "2009-03-18T17:06:21Z")

</div>

ms wrote:

> Hey,
> 
> thanks for reading this post. How do you handle dependencies? A really  
> simple example: I’ve got a table called “entity” and another table,  
> let’s say, “entity\_type”. The entity types can be changed, of course,  
> they also should be deletable, but only, if they are not used by some  
> entities! How can I ensure this in Rails or directly in the DBMS  
> (postgres)?

You need foreign key constraints in the database; check the Postgres  
docs for more details. I would _highly_ recommend using the  
foreign\_key\_migrations plugin, which will manage these constraints  
automatically from your migrations (it’s at  
[harukizaemon (Simon Harris) · GitHub](http://github.com/harukizaemon) , along with a lot of other good stuff).

Big tip: always make your constraints deferrable. It will make testing  
_much_ easier.

> Do I have to check it manually within a validate-method in  
> the model?

I suppose you could, but the DB will already do that if you have the  
constraints.

## Best,

Marnen Laibow-Koser  
removed\_email\_address@domain.invalid  
[http://www.marnen.org](http://www.marnen.org)
