嗨,我有一个团队表,然后是一个夹具模型:
class Fixture < ActiveRecord::Base
attr_accessible :away_score, :away_team_id, :home_score, :home_team_id, :result, :week
belongs_to :home_team, :class_name => 'Team'
belongs_to :away_team, :class_name => 'Team'
end
然后我有一个基于他们的团队ID生成灯具的程序,但我不确定在我的rails应用程序中添加它的位置,我试图在我已经创建的20个团队的视图中显示灯具但不确定怎么样?所以我的输出将是主队team_name,id为1,远离队team_name,id为2,夹具1等......
teams = Array(1..20)
fixed_team = teams.shift #The fixed competitor described in the algorithm
teams.length.times do |i|
#Create the two groups listed in the algorithm
teams = teams.rotate
week_teams = teams.dup.unshift(fixed_team)
first_group, second_group = week_teams.each_slice(week_teams.length/2).to_a
second_group.reverse!
weeks_pairings = first_group.zip(second_group)
#Output the week's pairings
puts "Week #{i + 1}: #{weeks_pairings}"
end
#Output:
#=> Week 1: [[1, 2], [3, 20], [4, 19], [5, 18], [6, 17], [7, 16], [8, 15], [9, 14], [10, 13], [11, 12]]
#=> Week 2: [[1, 3], [4, 2], [5, 20], [6, 19], [7, 18], [8, 17], [9, 16], [10, 15], [11, 14], [12, 13]]
#=> etc
答案 0 :(得分:1)
假设您的数据库(或更多)中有20个团队条目(具有属性name
):
teams = Team.first(20)
fixed_team = teams.shift #The fixed competitor described in the algorithm
teams.length.times do |i|
#Create the two groups listed in the algorithm
teams = teams.rotate
week_teams = teams.dup.unshift(fixed_team)
first_group, second_group = week_teams.each_slice(week_teams.length/2).to_a
second_group.reverse!
weeks_pairings = first_group.zip(second_group)
puts "Week #{i+1}: "
weeks_pairings.each do |pair_of_teams|
puts "#{pair_of_teams[0].name} vs. #{pair_of_teams[1].name}"
end
end
答案 1 :(得分:0)
您应该将算法的逻辑放在Fixture模型中;用静态方法模块化它,如
def self.show_fixtures
#add algo here
end
但是您必须修改代码以返回数组或其他一些数据结构。 现在你可以做到
Fixture.show_fixtures
无论在何处 - 在任何视图中,在控制器等中获得对战。
您还可以定义用于显示灯具的专用视图。首先,在FixtureController中添加一个动作
def show_fixtures
@list = Fixture.show_fixtures
end
然后,添加视图/views/fixture/show_fixtures.html.your_extension 在视图中,您可以迭代@list数组并为灯具中的每个匹配渲染部分。
答案 2 :(得分:0)
我没有得到你的代码所做的,但正如你在评论中所说,我建议你这样做。
在灯具中添加此方法。调用 Fixture.create_fixture
def self.create_fixture
weeks_pairings = []
teams = Team.all.map(&:name)
fixed_team = teams.shift #The fixed competitor described in the algorithm
teams.length.times do |i|
#Create the two groups listed in the algorithm
teams = teams.rotate
week_teams = teams.dup.unshift(fixed_team)
first_group, second_group = week_teams.each_slice(week_teams.length/2).to_a
second_group.reverse!
weeks_pairings << first_group.zip(second_group)
end
weeks_pairings #You can use this in view
end
在视图中:
<% Fixture.create_fixture.each_with_index do |week, games_list| %>
<%= "<h3> Week #{week+1} </h3>" %>
<ul>
<% games_list.each do |teams| %>
<li><b><%= "#{teams.first} Vs #{teams.last}" %></li>
<% end %>
</ul>
<% end %>