订购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
排序的配置文件。