mysql - 使用 id 从表中检索值

标签 mysql ruby-on-rails ruby model

嗨,我有一个团队表,然后是一个夹具模型:

 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 个团队的 View 中显示灯具如何?所以我的输出将是带有 id 1 的主队 team_name 和带有 id 2 的客队 team_name 对于 fixture 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

最佳答案

假设您的数据库中有 20 个 Teams 条目(具有属性 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

关于mysql - 使用 id 从表中检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14588651/

相关文章:

php - 调用成员函数 row() 错误 | $row = $query->row(); |代码点火器

ruby-on-rails - 在 Netbeans/JRuby 中开发 Rails 应用程序但部署到 Ruby (C)

ruby-on-rails - 订阅的短信支付平台?

java - Java 中的 "caller"和 Ruby 中的 "receiver"一样吗?

mysql - 如何解决在亚马逊托管 jboss Web 应用程序时数据库连接被拒绝的问题

mysql - 按月透视 MySQL 中的数据

mysql - sql 中的两个计数,但在不同的列中

css - Rails 似乎要求我在 CSS 对 Development 生效之前进行预编译

ruby - bundler 清理下载的 gits

ruby-on-rails - Controller Spec#Show Action : exoected: [Object], 得到:无错误 - RSpec 3