Reputation: 663
I have two models:
class Country
has_many :competitions
end
class Competition
belongs_to :country
end
Competition class has a position attribute. Admin can sort competitions by position. I want to sort countries with the minimum position of its competitions. I also want to joing competitions with country. How can i achieve that?
I want an output like:
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)
Upvotes: 0
Views: 1037
Reputation: 52356
I think you'd have to:
Country.order("(select min(position) from competitions where competitions.country_id = countries.id) asc")
I'm not sure how that syntax holds up across different RDBMSs -- should be good on PostgreSQL and Oracle
Upvotes: 1