我有一个相当标准的商业模式,Account
个实例可以互相关注。它就像Twitter一样。连接模型称为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
我想查看跟随两个或更多其他特定帐户的推特帐户。
例如,假设数据库中存在四个帐户。他们将艾伦,贝卡,查理和戴夫命名为。戴夫跟随艾伦和查理。贝卡只跟随艾伦。当我应用我的范围时,它应该只返回Dave。
我可以查看关注一个特定帐户的用户:
Account.includes(:active_relationships)
.where(relationships: { followed_id: alan.id })
但链接where子句返回零的结果,因为DB查找关系记录,其中followed_id
同时等于两个不同的帐户ID。这显然是不可能的。
Account.includes(:active_relationships)
.where(relationships: { followed_id: alan.id })
.where(relationships: { followed_id: charlie.id })
如何使用ActiveRecord正确实现此功能?