从 ruby 中的数组中检索实例
Retrieving instance from array in ruby
我有一个 scoreboard
有很多 games
。 game
has_many users
和 user
has_many games
,所以我有一个连接 table/model game_users
。
Scoreboard
belongs_to competition
。我的管理员可以生成与比赛相关的记分牌。
这个想法是在该记分牌上生成记分牌和 (@competition.users.count / 2
) 场比赛(前提是我们有偶数的玩家)。一场比赛是2名球员之间的对抗。
在我的 scoreboard_controller 中,我有 :
def create
@scoreboard = Scoreboard.new
@scoreboard.competition = @competition
authorize @scoreboard
if @scoreboard.save
if @competition.users && @competition.users.count.even?
@total_players = @competition.users
num = 0
for num in 0..(@competition.users.count / 2) do
game = Game.new(scoreboard: @scoreboard)
game.save
gameUserFirst = GameUser.new(game: game, user: @total_players.sample)
@total_players = @total_players.except(gameUserFirst.user)
gameUserSecond = GameUser.new(game: game, user: @total_players.sample)
@total_players = @total_players.except(gameUserSecond.user)
gameUserFirst.save
gameUserSecond.save
num += 1
end
end
redirect_to competition_scoreboard_path(@competition, @scoreboard)
else
end
end
我的目标是在随机玩家之间生成游戏,但我不希望玩家被选中两次或与自己对战。为了防止这种情况,一旦在 GameUser
对象中使用,我想从 @total_players
数组中检索它。
不幸的是 .except
方法似乎不适用于实例。我怎样才能做到这一点?
使用-=
代替except
:
@total_players -= [gameUserFirst.user]
但我建议另一种创建匹配的方法:您可以创建一个包含所有用户 ID 的数组,将其打乱,然后选择组合:
@competition.user_ids.shuffle.in_groups_of(2).each do |user_id_1, user_id_2|
# Create game...
end
还有一点:控制器中有那么多业务逻辑通常不是一件好事。可以放在 Scoreboard
模型中的 after_create
方法中。
我有一个 scoreboard
有很多 games
。 game
has_many users
和 user
has_many games
,所以我有一个连接 table/model game_users
。
Scoreboard
belongs_to competition
。我的管理员可以生成与比赛相关的记分牌。
这个想法是在该记分牌上生成记分牌和 (@competition.users.count / 2
) 场比赛(前提是我们有偶数的玩家)。一场比赛是2名球员之间的对抗。
在我的 scoreboard_controller 中,我有 :
def create
@scoreboard = Scoreboard.new
@scoreboard.competition = @competition
authorize @scoreboard
if @scoreboard.save
if @competition.users && @competition.users.count.even?
@total_players = @competition.users
num = 0
for num in 0..(@competition.users.count / 2) do
game = Game.new(scoreboard: @scoreboard)
game.save
gameUserFirst = GameUser.new(game: game, user: @total_players.sample)
@total_players = @total_players.except(gameUserFirst.user)
gameUserSecond = GameUser.new(game: game, user: @total_players.sample)
@total_players = @total_players.except(gameUserSecond.user)
gameUserFirst.save
gameUserSecond.save
num += 1
end
end
redirect_to competition_scoreboard_path(@competition, @scoreboard)
else
end
end
我的目标是在随机玩家之间生成游戏,但我不希望玩家被选中两次或与自己对战。为了防止这种情况,一旦在 GameUser
对象中使用,我想从 @total_players
数组中检索它。
不幸的是 .except
方法似乎不适用于实例。我怎样才能做到这一点?
使用-=
代替except
:
@total_players -= [gameUserFirst.user]
但我建议另一种创建匹配的方法:您可以创建一个包含所有用户 ID 的数组,将其打乱,然后选择组合:
@competition.user_ids.shuffle.in_groups_of(2).each do |user_id_1, user_id_2|
# Create game...
end
还有一点:控制器中有那么多业务逻辑通常不是一件好事。可以放在 Scoreboard
模型中的 after_create
方法中。