【发布时间】:2015-02-08 22:07:18
【问题描述】:
我正在尝试通过一个相当复杂的关联来订购查询,但没有运气。
这里是模型的相关部分...
class Athlete < ActiveRecord::Base
has_many :participations
has_many :matches, :through => :participations
scope :active, -> { where(active: true) }
end
class Participation < ActiveRecord::Base
belongs_to :athlete
belongs_to :match
end
class Match < ActiveRecord::Base
has_many :participations, :dependent => :destroy
has_many :athletes, :through => :participations
scope :unplayed, -> { where("started_at is NULL and year=2015") }
end
我需要通过“athlete.matches.unplayed.count”订购一系列运动员。所以我有 has_many :through 关联来处理以及 Match 上的“未播放”范围。
在回应评论时增加清晰度。具体来说,我在视图中有这张表:
<% @athletes.each do |athlete| %>
<% match = athlete.matches.in_progress.first %>
<tr>
<td><%= athlete.full_name %></td>
<td><%= athlete.idle? ? "Idle" : "Playing" %></td>
<% if athlete.idle? %>
<td></td>
<td></td>
<td></td>
<% else %>
<td><%= match.sport_name %></td>
<td><%= match.arena_name %></td>
<td><%= match.elapsed_time_string %></td>
<% end %>
<td><%= athlete.matches.unplayed.count %></td>
</tr>
<% end %>
我想要表格,因此@athletes,按我显示“athletes.matches.unplayed.count”的最后一列排序。
从控制器,@athletes 是:
@athletes = Athlete.active
提前致谢!
【问题讨论】:
-
order是什么?想要的结果是什么? -
我需要按照“athlete.matches.unplayed.count”在rails中返回的内容对返回的运动员组进行排序。
-
cool.. 显示控制器操作,您在其中设置
@athletes的值 .. -
你试过
@athletes = Athlete.active.order('coulmn')吗?column是您要对结果集进行排序的列的名称。 -
什么是“列”?我订购的运动员模型中没有任何部分。它是对通过关联获得的特定范围匹配的计数。这就是困难。
标签: ruby-on-rails ruby-on-rails-3.2