【问题标题】:Order through association通过关联订购
【发布时间】: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


【解决方案1】:

我创建了这个范围

scope :order_by_machets_unplayed, ->
  {joins(:matches).where('matches.started_at is NULL and matches.year=2015').group('athletes.id').order("count(matches.id) desc")} 

不优雅,但有效

  • 优点: 数据库对您的元素进行排序,而不是 ruby​​
  • 缺点
    • 不干燥
    • 读起来不简单

【讨论】:

  • 这是运动员模型的范围吗?
  • 我知道,不干燥:/。但我告诉你,这是部分解决方案。您需要在 Athlete 中创建一个新字段来存储该计数。之后,如果比赛发生变化,您可以更新您的计数
猜你喜欢
  • 1970-01-01
  • 2011-01-13
  • 1970-01-01
  • 1970-01-01
  • 2013-01-06
  • 1970-01-01
  • 2019-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多