Foreign Key Contraints in RoR

0 views
Skip to first unread message

bmcc

unread,
Dec 16, 2009, 10:54:19 AM12/16/09
to Orlando Ruby Users Group Discussion
I was wondering how important are foreign key contraints in rails?
Some people say if you dont have them then your application is broken.
The reason i am asking is because I have a few tables that are related
to themselves through a has_many/belongs_to relationship. For example
lets say I have a model called article that could exist on its own or
belongs_to a newspaper (model). If it is a solo article then the
foreign key newspaper_id will be null. This is a problem for key
contraints isn't it?

t.integer :newspaper_id, :null => false, :options =>
"CONSTRAINT fk_article_newspapers REFERENCES newspapers(id)"

This is a book example (Agile Web Development with Rails, 3rd Edition)
of setting a foreign key in rails, and null is not allowed. I was
wondering if there was a way to keep key contraints but allow null
foreign keys incase I decided to break the relationships apart freely?

Chris Booth

unread,
Jan 14, 2010, 7:13:29 AM1/14/10
to Orlando Ruby Users Group Discussion
Are you talking about how Rails handles FKs or how the db handles
them?

In the case of PostgreSQL (and I'm pretty sure MySQL), I know that FK
fields can contain null values without an issue. They just can't
contain non-null, invalid values. Also, I'm pretty sure that unless
your Rails model has a validates_presence_of :your_fk_field, that
Rails won't squawk either (unless for some reason the db you're using
has an issue with this and spits back an error).

The one thing I think you would have to be careful of here is if your
FK field is part of a unique index on that table. On some db's, this
will be an issue since they don't allow null values to be part of a
unique key or more than one null value in a unique key is not allowed
(because it makes the entire key null). However, that's related to
the db, and not Rails itself.

Hope that helps!

--Chris

Reply all
Reply to author
Forward
0 new messages