这里有几个指针。
belongs_to_many 不是一个东西,至少在我熟悉的最新版本中是这样。也许你的意思是has_and_belongs_to_many 或者可能是has_many :groups, through: :memberships。我将在下面使用后一种形式。
为了在Group 类中使用through :groups 选项,您首先需要定义一个:groups 关联。如果您试图将其定义为任何其他具有User 的Group 和Group 的成员,那么您可以轻松地做到这一点:
class Membership
belongs_to :user
belongs_to :group
end
class User
has_many :memberships
has_many :groups, through: :memberships
end
class Group
has_many :memberships
has_many :users, through: :memberships
has_many :groups, through: :users
end
您可能希望重命名此关联以减少混淆:
has_many :connected_groups, through: :users, source: :groups
现在您想在Group 上定义另一个 users 关联,它代表任何连接组的用户。您需要一个不同的名称,您无法有意义地定义两个同名的关联(您将如何访问一个与另一个?)。所以我建议使用名称connected_groups 和connected_users,或类似名称:
class Group
has_many :memberships
has_many :users, through: :memberships
has_many :connected_groups, through: :users, source: :groups
has_many :connected_users, through: connected_groups, source: :users
end