我有一个ActiveRecord对象,称为contact
。它具有称为的关系profiles
。这些配置文件具有url属性。配置文件应按url的字母顺序排序。我已经尽力sort_by
了,order
但是出现了这个错误:
contact.profiles.sort_by! { |profile| profile.url }
undefined method `sort_by!' for #<Profile::ActiveRecord_Associations_CollectionProxy:0x00000105d6d430>
最好的方法是什么?我正在使用Rails v4.1.0。
使用订单查询方法根据url
属性对档案记录进行排序Profile
contact.profiles.order(url: :desc) ## sort in descending order
对于升序,您可以指定asc
而不是desc
。
更新
第二点,如果您希望检索始终按其排序的概要记录,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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句