Rails: Look for the has_one entry that doesn't have

So, I have an application with two models. Foo has_one Bar, Bar belongs to_to Foo.

Now, to create a Foo, you have to create a Bar in order to belong to it, but something seems to have slipped through the cracks, because in my production application I now seem to have one Foo that is somehow created without a bar and this causes a 500 error.

Now here is the problem:

I can search: Bar.where(:foo=>nil) just fine. But orphans are not a problem, and that does not tell me what I need.

I need to find one Foo where Bar is nil. But the database stores the relationships in the Bars table, i.e. BarsTable has foo_id, there is nothing in FoosTable to tell me that it does not have a bar.

When I use Foo.find(#).bar , I get zero for one dummy entry, but I have many entries.

So, can someone tell me how to build a query that will return the Foo that is not in it?

Thanks!!

+7
source share
3 answers

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

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

+7
source

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

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

This will return an array of Foo objects that do not have an associated Bar object.

In this method, you do not rely on information about a specific table. If the foreign_key column was supposed to change in the future Foo → Bar association, this method will continue to work.

+2
source

For future users, another way to do this is to

 Foo.all.where.not(id: Bar.pluck(:belongs_to_id)) 

This makes two requests, one for pluck and one for Foo.where.not (id: plucked_ids).

0
source

All Articles