我有两个模型。位置和SportPosition。
Position.rb
attr: id, name
has_many :sport_positions
SportPosition.rb
attr: sport_id, position_id
belongs_to :position
我想使用一种排序方法,如下所示,我通过sport_position按位置名称对字母进行排序。如何按模型关系排序?
def sorted_positions
sorted = sport_positions.sort_by(position__name)
end
答案 0 :(得分:1)
可能的解决方法如下:
在您的模型SportPosition.rb
中def self.sorted_positions
.joins(:position).order("LOWER(positions.position_name) ASC")
end
sorted = SportPosition.sorted_positions #you will get all the sport_positions associated with the position and these sport_positions will be sorted/ordered with position name in ascending order.
答案 1 :(得分:0)
这应该有效,@ position是Position的实例/对象
sorted = @position.sport_positions.order('position__name ASC')