订购ActiveRecord关系对象

我有一个名为contact的ActiveRecord对象。 它有一个称为profiles的关系。 这些配置文件具有url属性。 应按字母顺序按URL排序配置文件。 我尝试过sort_by以及order但是我收到了这个错误:

 contact.profiles.sort_by! { |profile| profile.url } undefined method `sort_by!' for # 

最好的方法是什么? 我正在使用Rails v4.1.0。

使用订单查询方法根据Profile url属性对Profile文件记录进行排序

 contact.profiles.order(url: :desc) ## sort in descending order 

对于升序,您可以指定asc而不是desc

UPDATE

在第二个注释中,如果要检索始终url排序的配置文件记录,请将Contact模型更新为:

 class Contact < ActiveRecord::Base # ... has_many :profiles, -> { order url: :desc } ## change order as per your requirement to asc / desc # ... end 

在此之后, contact.profiles 总是会根据url排序的配置文件。