Rails 4活动记录:按关联排名

时间:2013-08-14 21:17:05

标签: ruby-on-rails activerecord ruby-on-rails-4

我有两种模式:

class Country
  has_many :competitions
end

class Competition
  belongs_to :country
end

比赛类有一个位置属性。管理员可以按位置对比赛进行排序。我想对排名最低的国家进行排序。我也想和国家一起参加比赛。我怎样才能做到这一点?

我想输出如下:

X Country: (is at first order because Xcomp1's position is 1)
  Xcomp1 (position: 1)
  Xcomp2 (position: 12)

A Country: 
  Acomp1 (position:2)
  Acomp2 (position:3)

Z Country: (is at last position because minimum position of its competitions are higher than other ones)
  Zcomp1 (position:5)

1 个答案:

答案 0 :(得分:1)

我认为你必须:

Country.order("(select min(position) from competitions where competitions.country_id = countries.id) asc")

我不确定这种语法在不同的RDBMS中是如何保持的 - 应该在PostgreSQL和Oracle上很好用