I'm have a fairly standard business model with Account
instances who can follow each other. It's just like Twitter. The join model is called Relationship
.
class Account
has_many :active_relationships, class_name: 'Relationship',
dependent: :destroy, foreign_key: :follower_id
has_many :passive_relationships, class_name: 'Relationship',
dependent: :destroy, foreign_key: :followed_id
# These are accounts that a given account is following
has_many :friends, through: :active_relationships, source: :followed
# These are accounts that follow the given account
has_many :followers, through: :passive_relationships, source: :follower
end
class Relationship
belongs_to :follower, class_name: 'Account'
belongs_to :followed, class_name: 'Account'
end
I'd like to scope to twitter accounts which follow two or more other specific accounts.
For example, imagine four accounts exist in the database. They're named Alan, Becca, Charlie and Dave. Dave follows both Alan and Charlie. Becca only follows Alan. When I apply my scope it should return Dave only.
I can scope to users who follow one specific account like this:
Account.includes(:active_relationships)
.where(relationships: { followed_id: alan.id })
but chaining where clauses returns zero results because the DB looks for a relationship record where the followed_id
is simultaneously equal to two different account ids. This is obviously impossible.
Account.includes(:active_relationships)
.where(relationships: { followed_id: alan.id })
.where(relationships: { followed_id: charlie.id })
How do I implement this correctly with ActiveRecord?