domi91c
domi91c

Reputation: 2053

Find all Users with conditions of nested association - Rails 4

I'm trying to find all Users who have replied to a particular post.

Users have many Messages. Messages have one Conversation. I'm using a column on the Conversation table called related_object_id to make sure it relates to the right post.

I've tried things like this:

1.  User.all.where(:messages.conversation(:related_object_id => post))

2.  User.all.where(messages.select {|m| m.conversation.where(:related_object_id => post)})

Pretty bad attempts (I know I can't access the messages association through where like that) but hopefully it gives you an idea of what I'm trying to do.

Upvotes: 0

Views: 69

Answers (1)

cschroed
cschroed

Reputation: 6834

Try something like:

User.joins(messages: :conversation).where(conversations: { related_object_id: post }).uniq

Upvotes: 1

Related Questions