Rails - 与组、用户、所有者、成员协会有困难

Rails - having difficulty with group, user, owner, member associations

我找遍了所有地方,却找不到我要找的东西。我知道我需要什么,但无法将 2 和 2 放在一起。

此代码不正确,但想法是这样的:

class Group < ActiveRecord::Base
 has_one :owner, :class_name => "user"
 has_many :members, :class_name => "user"
end

class User < ActiveRecord::Base
 belongs_to :groups
 has_one :group, :class_name "user"
end

我认为我需要一个 has_many :through 关联,但不确定如何实现它。如何构建我的 models/controllers/migrations 以表示上述参数内的关联?

http://guides.rubyonrails.org/association_basics.html#the-types-of-associations

在这种情况下您可以使用并取决于您的要求的主要类型是

has_many :groups, through: join_table

其中加入 table 将通过 user_id 和 group_id 引用用户和组。这允许您获得与组成员身份相关的其他信息,也许您想要加入日期或成员身份 ID 或类似信息。

has_and_belongs_to_many :groups

以类似的方式实现,但绕过了连接模型,只会在关系的任何一侧为您提供 groups/users 的列表

多态关系不会真正发挥作用,除非您计划拥有不同类型的成员资格,可能是团体、组织或需要类似但独立的数据库 tables 的东西。

现代 Rails 应用程序使用 has_many through: 而不是 HABTM。

class User < ActiveRecord::Base

  has_many :groups, through: :user_groups

end

class Group < ActiveRecord::Base

  has_one  :owner, through: :user_groups, source: :user
  has_many :members, through: :user_groups, source: :user

end

class UserGroups < ActiveRecord::Base
  validates :owner, uniqueness: true
  belongs_to :member, class_name: 'User'
  belongs_to :group
  belongs_to :owner, class_name: 'User'
end

has_manyhas_one 上添加 source 允许您编写 Group.find(id).membersGroup.find(id).owner。在加入时验证组所有者的唯一性。

我也建议使用连接 table 如下:

class Membership < ActiveRecord::Base
  belongs_to :group
  belongs_to :user
end

class Group < ActiveRecord::Base
  belongs_to :owner, class_name: "User"
  has_many :members, through: :memberships, source: :user
  has_many :memberships
end

class User < ActiveRecord::Base
  has_one :owned_group, foreign_key: "owner_id", class_name: "Group"
  has_many :groups, through: :memberships
  has_many :memberships
end

迁移如下:

class CreateMemberships < ActiveRecord::Migration
  def change
    create_table :memberships do |t|
      t.references :user
      t.references :group

      t.timestamps null: false
    end
  end
end

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.timestamps null: false
    end
  end
end

class CreateGroups < ActiveRecord::Migration
  def change
    create_table :groups do |t|
      t.references :owner

      t.timestamps null: false
    end
  end
end