ruby-on-rails - 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
我怎样才能做到这一点?或者一种将团队随机均匀地分配到组的方法会更好,尽管不是绝对必要的。
解决方案
为了解决这个问题,您似乎想要获得所有回合组
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 组将是不均匀的(您必须做一些数学运算以确保组均匀)
希望这会有所帮助。
推荐阅读
- python - 如何在分组后获得模式的计数?
- azure - 在单个 Azure 存储脚本中为各种环境传递多个参数
- c - 为什么这两种情况下的输出不同
- sed - 使用 SED 从结果中删除以 http 开头的域名
- android - 同时使用 ProGuard 和 R8
- wolfram-mathematica - 在 Wolfram Mathematica 中使用命令 Print 和 Manipulate 打印表达式
- user-interface - 在 Unity2D 中将 Input.mousePosition 分配给 transform.position 时出现问题
- c# - ASP.NET Core WebApi Jwt 基于角色的授权不起作用
- function - 无法获取 /relatables-d98b3/us-central1/app/products
- java - 如何在 Retrofit 中自动将 json-root 属性反序列化为对象?