Wednesday, November 17, 2010

Rails 3 + Foreign Key

Hi there !

Recently I've been doing some railing on rails 3. They're pretty cool actually but you can read about it elsewhere ;)

Though, there is this "foreign key" problem. Rails != Hibernate so sometimes we must work some magic.
We cannot do native foreign keys so we'll do it the "hard way" (which is btw very easy)
I'm using PostgreSQL (if you aren't - you should !) This method will probably won't work for other databases but I don't care, so...
We take our migration file and put there :
t.column :site_id, 'integer references sites(id)', :null => false
t.column :user_id, 'integer references users(id)', :null => false
t.column :parent, 'integer references comments(id)'
or something similar.
And that's it ! We don't need any plugins. Foreign keys are created.
Foreign-key constraints:
    "comments_parent_fkey" FOREIGN KEY (parent) REFERENCES comments(id)
    "comments_site_id_fkey" FOREIGN KEY (site_id) REFERENCES sites(id)
    "comments_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id)
Referenced by:
    TABLE "comments" CONSTRAINT "comments_parent_fkey" FOREIGN KEY (parent) REFERENCES comments(id)
That's so awesome, isn't it ?

1 comment:

Un tipo said...

Excellent man, I'll test your solution :)