Foreign keys in Ruby on Rails

Should the foreign key constraints only be declared in the Model code of
the application, or in both the code and the database?

Thanks for any hints,
Lieven

Lieven De Keyzer wrote:

Should the foreign key constraints only be declared in the Model code of
the application, or in both the code and the database?

Or better yet, only in the database.

You really want the database to take of these constraints since that is
the piece of software that will be handing your data. Of course, you may
add them to the model code but I think that would be redundant.

  • Adam

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Nov 18, 2005, at 10:06 AM, Adam M. wrote:

you may
add them to the model code but I think that would be redundant.

Putting them in the model makes error handling easier and more
naturally expresses your domain model. Putting them in the database
is easy, so why not; it’s a nice fallback.

jeremy
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (Darwin)

iD8DBQFDfjnpAQHALep9HFYRAv5mAJ475shrES6ziYA6NLw6ECPhqBJOXgCePol6
E/TJ2sl6y58B0pneix5obag=
=/lzQ
-----END PGP SIGNATURE-----

On 11/18/05, Adam M. [email protected] wrote:

the piece of software that will be handing your data. Of course, you may
add them to the model code but I think that would be redundant.

  • Adam

That depends. I have an application that supports postgresql, mysql, and
sqlite. Since sqlite doesn’t support foreign keys I have to put it in
the
model even though it’s redundant for postgresql and mysql.

Chris

snacktime wrote:

That depends. I have an application that supports postgresql, mysql,
and sqlite. Since sqlite doesn’t support foreign keys I have to put
it in the model even though it’s redundant for postgresql and mysql.

It does support foreign keys, just doesn’t enforce them.

http://www.justatheory.com/computers/databases/sqlite/

see bottom of that page entitled “Enforce Foreign Key Integrity in
SQLite with Triggers”. But on the other hand emulating FK constraints
with Rails is not difficult.

  • Adam