With ActiveRecord, how do I get all records from database with only one associated record?

With ActiveRecord, how do I get all records from database with only one associated record?

For example: I have two tables, table_a has many related records in table_b.

I want to make an ActiveRecord query that will fetch me only the table_a query objects that have *only one associated records in table_b*.

How would I go about doing this?

Thanks!

Answers


Well I'm not aware of any nice and easy way to do this in rails, but I have got together a raw sql query that you can fire using ActiveRecord::Base.connection.execute. Let me tell you that it's probably the most ugly query I have ever built, so sorry about that :-)

SELECT ta.* FROM table_a AS ta INNER JOIN table_b AS tb ON ta.id = tb.table_a_id WHERE
  tb.id IN ( SELECT temp.id FROM (
    SELECT id, count(*) AS count FROM table_b GROUP BY table_a_id
  ) AS temp WHERE temp.count=1 ) GROUP BY ta.id;

Need Your Help

Handler pattern in Project Silk

design-patterns repository handler

I am looking at the source for the Project Silk project and there is a "handler" pattern that I have not seen before. First - this link from 2009 alludes to it but leaves me hanging