决定团队领导并将用户分配给ruby on rails

时间:2013-05-26 09:39:13

标签: ruby-on-rails ruby database

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

怀疑:1。在创建团队时,这是将team_lead列放在团队表中以将团队领导分配给团队的正确方法。

  1. 创建团队时,它将拥有团队领导和一些已经存在于db中的用户。如何将用户分配给团队?
  2. user.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
    

    team.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
    

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

1 个答案:

答案 0 :(得分: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 documentation

相关问题