I have two models, Conversation and Phones, both of which has_and_belongs_to_many each other. Phones can have a lot of conversations, and conversations can have a lot of phones (two or more).
class Conversation < ActiveRecord::Base
has_and_belongs_to_many :phones
end
class Phone < ActiveRecord::Base
has_and_belongs_to_many :conversations
end
Of course, there's a conversations_phones join table as well.
If I have two or more phone objects, how do I find a list of all the conversations they share? The catch: the conversations can't include any other phones (IE the number of phone IDs equals the number we search with).
I've been able to do it with pure Rails, but it involves looping every conversation and counting on the db. Not good.
I don't mind doing pure SQL; using the model IDs should help stop injection attacks.
The closest I've come is:
SELECT conversations.* FROM conversations
INNER JOIN conversations_phones AS t0_r0 ON conversations.id = t0_r0.conversation_id
INNER JOIN conversations_phones AS t0_r1 ON conversations.id = t0_r1.conversation_id
WHERE (t0_r0.phone_id = ? AND t0_r1.phone_id = ?), @phone_from.id, @phone_to.id
But it includes conversations with outside phones. I have a feeling GROUP BY and HAVING COUNT would help, I'm just too new to SQL.