1

我有两张桌子,usersgroups。用户拥有一个组,并且可以属于多个组。一个组属于一个用户,可以有多个用户。

因此,对于我的user模型,我有

has_and_belongs_to_many :groups
has_many :groups

而对于我的group模型,我有

has_and_belongs_to_many :users
belongs_to :user

我的迁移中也有一个连接表..

def change
  create_table :groups_users, :id => false do |t|
    t.integer :group_id
    t.integer :user_id
  end
end

我的问题是这有意义吗?我觉得has_manybelongs_tohas_and_belongs_to_many.

4

2 回答 2

2

我会采用的方法,这是我自己的个人方法,使用 3 个表/模型,如下所示:

group_user.rb

class GroupUser < ActiveRecord::Base
  attr_accessible :user_id, :group_id

  belongs_to :group
  belongs_to :user
end

组.rb

class Group < ActiveRecord::Base
  attr_accessible :owner_id

  validates_presence_of :owner_id

  has_many :group_users
  has_many :users, through: :group_users
end

用户.rb

class User < ActiveRecord::Base
  attr_accessible :some_attributes

  has_many :group_users
  has_many :groups, through: :group_users
end

然后,无论何时创建一个Group对象,User创建它的对象都会将其id放置在表的owner_id属性中,Group并将其本身放入GroupUser表中。

于 2013-02-06T18:55:35.597 回答
2

为了不让多个外键指向同一个关系,另一种选择是使用连接模型,然后在连接模型上添加一个标志来表示用户是否是所有者。

例如:

class User < ActiveRecord::Base
  has_many :memberships
  has_many :groups, through: :memberships
  has_many :owned_groups, through: memberships, conditions: ["memberships.owner = ?", true], class_name: "Group"
end

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

  #This model contains a boolean field called owner
  #You would create a unique constraint on owner, group and user
end

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, through: :memberships
  has_one :owner, through: :memberships, conditions: ["memberships.owner = ?", true], class_name: "User"
end
于 2013-02-06T18:56:44.937 回答