Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Find the "has_one" record that doesn't have one

So, I have an app with two models. Foo has_one Bar, Bar belongs_to Foo.

Now, to create a Foo you must to have to create a Bar to belong to it, but it looks like something slipped through the cracks because in my production app I now seem to have one Foo that somehow got created without a Bar, and it causes a 500 error.

Now, here's the problem:

I can search: Bar.where(:foo=>nil) just fine. But orphan bars aren't a problem, and this doesn't tell me what I need.

I need to find the one Foo where Bar is nil. But the database stores the relationship in the Bars table, ie, BarsTable has foo_id in it, there's nothing in the FoosTable to tell me it's missing a bar.

When I use Foo.find(#).bar I would get nil for the one bogus record, but I have a lot of records.

So, can anyone tell me how to construct a query that would return the one Foo that is missing it's Bar?

Thanks!!

like image 381
Andrew Avatar asked Apr 08 '11 13:04

Andrew


2 Answers

I'm not sure what the Ruby code would be, but I think the SQL should be something like:

SELECT * FROM Foo WHERE id NOT IN (SELECT foo_id FROM Bar)

like image 128
salexander Avatar answered Sep 21 '22 00:09

salexander


Another way (without using SQL) would be to do something like:

Foo.all.select{ |f| !f.bar }

This would return an array of Foo objects which don't have a related Bar object.

In this method, you're not relying on specific table information. If the foreign_key column were to change in the future Foo -> Bar association, this method would continue to work.

like image 29
Kevin Galens Avatar answered Sep 22 '22 00:09

Kevin Galens