0

我想显示一个表单来添加或编辑结果(如果存在)。我有一个 n * n 的表格,其中单元格中的 n 个团队由结果给出。这有多好?

view/championship/show.erb
<table class="table table-bordered">
  <tr><th>&nbsp;</th>
    <% @teams.each do |teamhome| %>
    <th class="vertical"><%= teamhome.name %></th>
    <% end %>    
  </tr>
  <% @teams.each do |teamguest| %>
  <tr>
    <th><%= teamguest.name %></th>
    <% @teams.each do |teamhome| %>
      <%if teamhome == teamguest %>
        <td bgcolor = '#F9F9F9'>
      <% else %>
        <td> 

         #render form               


        </td>
      <% end %>
    <% end %>
  </tr>
  <% end %>
</table>

楷模

class Score < ActiveRecord::Base
  attr_accessible :team1_score, :team2_score, :team1_id, :team2_id, :team1, :team2

  belongs_to :team1, class_name: 'Team', foreign_key: :team1_id
  belongs_to :team2, class_name: 'Team', foreign_key: :team2_id

  def self.to_arr

    score_arr = self.find(:all, :select => 'team1_id, team2_id, team1_score, team2_score').to_a

  end


end


class Team < ActiveRecord::Base
  attr_accessible :name

  belongs_to :championship
  has_many :team1_scores, class_name: 'Score', foreign_key: :team1_id
  has_many :team2_scores, class_name: 'Score', foreign_key: :team2_id

  validates :name, presence: true, length: { maximum: 100 }
  validates :championship_id, presence: true


end

图式

“team1_id”|“team2_id”|“team1_score”|“team2_score”

4

1 回答 1

0

一种方法是将所有分数加载为以下形式的哈希{ [:team1_id, :team2_id] => [:team1_score, :team2_score] }

@scores = Score.all.inject({}) do |m, s| 
  m[[s.team1_id, s.team2_id]] = [s.team1_score, s.team2_score]
  m
end

现在您可以像这样呈现每个家庭/客人配对的分数:

<% scores = @scores[[teamhome.id, teamguest.id]] %>
<%= "#{scores.first} / #{scores.last}" if scores %>

这种方法的优点是您可以通过哈希键找到匹配分数,即使对于大量数据也应该相当快。缺点是这个散列正在加载所有分数 - 甚至那些不包含在@championship. 如果你想避免这个问题,你可以建立一个范围来缩小相关团队的分数。然后只需调用Score.your_scope而不是Score.all.

另一种方法(不需要构建哈希)是直接从主队获取分数并检测该客队单元格的适当匹配:

<% scores = teamhome.team1_scores.detect{|s| s.team2_id == teamgues.id }
<%= "#{scores.team1_score} / #{scores.team2_score}" if scores %>

如果您没有过多的数据,那么这种更简单的方法就足够了。只需确保在最初加载球队时立即加载主队得分,否则您的表现将受到 N+1 查询的影响。

更新

在这两种方法中,分数都呈现为"home_team_score / guest_team_score",但前提是找到匹配的分数。如果未找到,则不呈现任何内容 - 这是由于if scores条件语句。如果要渲染其他内容,可以更改条件以使用三元运算符。下面的示例遵循第二种收集分数的方法:

<%= scores ? "#{scores.team1_score} / #{scores.team2_score}" : "No Score" %>

'No Score'如果未找到匹配的分数集,这将呈现。

于 2013-04-15T21:43:21.293 回答