I have an HABTM association between two models, User and Conversation.
I want to be able to query the logged-in user's conversations (current_user.conversations
), passing it another user's id, and have it return a conversation that is shared by both users, if one exists.
(an additional perk would be to have the query create one if one doesn't exist.)
The associations are working fine, so I can access the associated objects through instance variables like @user.conversations
and @conversation.users
, so I could go the long way and loop through each conversation object and search the user associations in each of them... But there must be an efficient way to construct this query.
What I would like to be able to do is something like current_user.conversations.where(conversation.users.exists?(id: @user_id))
or something like Conversation.find(users: {id: @user_id AND current_user.id})
.
I imagine there is an obvious answer to this, and I've been searching around here for similar questions but haven't found any. After looking through the Rails API docs, I imagine that the solution I'm looking for involves .includes()
in some way, but I can't get it working.
Any advice? Thanks.