【问题标题】:Rails group model that can own groups that can own users可以拥有可以拥有用户的组的 Rails 组模型
【发布时间】:2016-05-11 18:01:42
【问题描述】:

我正在尝试找出如何为我的应用程序建模组和用户,但我无法找到正确的方法。

我有用户,也有管理员。我还没有组模型。我希望一个组能够拥有多个用户,并且用户可以拥有多个组。更复杂的是,组可以通过其他组拥有多个用户。

class Group
  belongs_to :admin
  has_many :users
  has_many :users, through: :groups
end


class User
  belongs_to_many :groups
end

class Admin
  has_many :groups
end

我想我需要一张会员表。然后每个用户将通过成员资格连接到一个组。但是我怎么能连接组 --> 组 --> 用户呢?

class Membership
  ?
end

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    这里有几个指针。

    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
    

    【讨论】:

      猜你喜欢
      • 2013-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多