【问题标题】:Rails has_many and has_many throughRails 通过 has_many 和 has_many
【发布时间】:2017-09-22 01:23:15
【问题描述】:

我对如何解决这个问题感到困惑。我通过会员模型连接用户和组,但我也希望用户能够创建新组。显然,一个组必须属于一个用户,但这些组也通过成员资格表属于用户。

我的 user.rb 文件中有这个,但我觉得它是错误的。我是否删除了第一个并只使用了一个?在这种情况下,我如何在组的创建者中工作?

class User < ApplicationRecord
  has_many :groups
  has_many :groups, through: :memberships
end

也就是说,用户是很多组的成员,同时也是很多组的创建者。成员资格表只有两列(组 ID 和用户 ID)。此列中的用户 ID 用于存储属于该组的用户。我被困在如何处理创建组的用户上。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5


    【解决方案1】:

    您应该在组和用户之间建立两种关系。一个反映用户创建了一个组,另一个反映用户属于一个组。您可以通过配置关系的命名来反映这个想法。您还必须将 user_id 字段添加到您的 Groups 表中。

    class User < ApplicationRecord
      has_many :created_groups, class_name: "Group"
      has_many :memberships
      has_many :groups, through: :memberships
    end
    
    class Group < ApplicationRecord
      belongs_to :creator, class_name: "User"
      has_many :memberships
      has_many :subscribers, through: :memberships, source: :user
    end
    
    class Membership < ApplicationRecord
      belongs_to :user
      belongs_to :group
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-18
      • 2011-11-19
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多