0

我想为团队分配团队负责人和成员(用户)。我已经在团队和用户表之间创建了“具有多个直通”关联,因为一个团队可能有很多用户,并且一个用户可以分配给多个团队。为了获得每个团队的团队领导,我将 team_lead 列放在了团队表中。

疑问: 1.在创建团队时,将 team_lead 列放入团队表中以将团队领导分配给团队是否正确。

  1. 创建团队时,它将有一个团队负责人和一些用户,这些用户已经存在于数据库中。如何将用户分配给团队?

用户.rb

class User < ActiveRecord::Base
    has_many :teams, through: :user_teams
    has_many :user_teams
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :username, :email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :is_admin, :contact_no, :birth_date, :joining_date, :is_active, :is_hr, :is_manager
  # attr_accessible :title, :body
end

团队.rb

class Team < ActiveRecord::Base
  attr_accessible :name
  has_many :user_teams
  has_many :users, through: :user_teams
end

team_user.rb

class TeamsUser < ActiveRecord::Base
  attr_accessible :team_id, :team_lead, :user_id
  belongs_to :user
  belongs_to :team
end

在创建团队时,我想将团队负责人和用户分配给团队。如何实现这一点。任何帮助,将不胜感激。谢谢。

4

1 回答 1

1

您可以使用 更轻松地为用户和团队之间的多对多关系建模has_and_belongs_to_many

然后您的模型将如下所示:

class User
  has_and_belongs_to_many :teams

  ...
end

class Team
  has_and_belongs_to_many :users
  has_one :team_lead, class_name: "User"

  ...
end

注意Team也有一个team_lead,它也是类型User

然后很容易创建一个具有团队领导的新团队:

team = Team.new
team.team_lead = existing_user1
team.users << existing_user2
team.save

要使多对多关系起作用,您还需要一个名为teams_users. 有关设置多对多关系的更多信息,请参阅Rails 文档。

于 2013-05-26T09:50:42.847 回答