Search code examples
ruby-on-railsormreferential-integrity

Referential integrity in Rails applications


I am new to rails, having come from Symfony (which was inspired by Rails).

I am used to defining my database schema in full, and make sure my tables are in 3NF, if necessary 4NF etc.

I couldn't find a way to explicitly specify the CONSTRAINTS at the database level, and after searching online, I came across several posts such as this one: Hacked Ref Integrity, which left me simply astonished.

Admittedly, the article I linked to is quite old, and hopefully, things would have improved by now.

The (apparent?) lack of RI in rails makes the whole framework seem quite amateurish by comparison to Symfony, which it inspired.

Please say it ain't so ...


Solution

  • The initial approach of rails was to put responsibility for this in the application domain. This was a conscious compromise, and you will find a lot of discussion about it, if you look for it

    However since more and more developers shared your concerns, there have indeed evolved several ways to recognize the databases role in this.

    As the article you mentioned also shows, you can actually explicitly specify a lot of the constraints in the migrations with the normal migrations:

    http://guides.rubyonrails.org/active_record_migrations.html#foreign-keys

    add_foreign_key :articles, :authors
    

    Or you can go one step further and use extensions like the schmea plus gem