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!!
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With