views:

76

answers:

1

So here's a quick question. I'm using Rails with a huge legacy database, and it has many broken foreign keys that need to be treated as nils.

So when I do: Foo.find(:all, :conditions => {...}, :include => :bar)

Rails with connect all bars with SELECT * FROM bars WHERE id IN (...). So far so good, just two sql queries.

Now the problem is that for broken fks, when I try to do foo.bar later, Rails tries to refetch bar with SELECT * FROM bars WHERE id = broken_id. Then it returns nil (correctly for me), but all those SELECT id= turn out to be a major performance issue, as it bombards mysql with too many sql queries.

Any easy way of checking if foo.bar is already set and if it's not just forcing it to nil?

+1  A: 

You can use the loaded? method to test if the association was already loaded:

foo.bar.loaded?

If you know for a fact that you used :include and foo.bar.loaded? returns false then you fell over a broken fkey, skip this foo.bar.

vladr