首页 > 解决方案 > Rails 一次将记录均匀地分配给组

问题描述

我有模型 Turn、TurnGroup、TurnTeam 和 TurnGroupTeam

转.rb

has_many :turn_groups
has_many :turn_teams

turn_group.rb

belongs_to :turn
has_many :turn_group_teams

turn_group_team.rb

belongs_to :turn_group
belongs_to :turn_team

turn_team.rb

belongs_to :turn
has_many :turn_group_teams

我正在尝试创建一种方法,一次将所有 turn_teams 分配给 turn_groups。到目前为止,我做了:

  def_assign_teams
  @turn_teams = @turn.turn_teams
  @turn_teams.each.do |turn_team|
  TurnGroupTeam.create(turn_team_id: turn_team.id, turn_group_id: ??? )
  end

我不知道如何分配 turn_group_id。像这样简单的东西就足够了:

TurnTeam 1,2,3,4,5,6
TurnGroup A,B 
TurnGroupTeam 1-A, 2-B, 3-A, 4-B, 5-A, 6-B

我怎样才能做到这一点?或者一种将团队随机均匀地分配到组的方法会更好,尽管不是绝对必要的。

标签: ruby-on-rails

解决方案


为了解决这个问题,您似乎想要获得所有回合组

def assign_teams

    index = 0
    @turn_teams = @turn.turn_teams
    turn_groups = @turn.turn_groups
    @turn_teams.each do |turn_team|
        TurnGroupTeam.create(turn_team_id: turn_team.id, turn_group_id: turn_groups[index].id )
        if index === turn_groups.count
            index = 0
        else
            index = index + 1
        end
    end
end

基本上,上述内容应该可以工作,您可以在一系列记录中获得所有回合组。之后,您将根据发生的循环次数分配 turn_groups id。

请注意,如果您采用上面的示例并添加 TurnGroup C,D 组将是不均匀的(您必须做一些数学运算以确保组均匀)

希望这会有所帮助。


推荐阅读