Search code examples
sqlruby-on-railsruby-on-rails-3findassociations

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!!


Solution

  • 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)