Order an ActiveRecord relation object

强颜欢笑 提交于 2019-12-22 18:38:30

问题


I have an ActiveRecord Object called contact. It has an relation called profiles. These profiles have a url property. The profiles should be ordered by url in alphabetical order. I've tried sort_by as well as order but I get this error:

contact.profiles.sort_by! { |profile| profile.url }
undefined method `sort_by!' for #<Profile::ActiveRecord_Associations_CollectionProxy:0x00000105d6d430>

What's the best way to do this? I'm using Rails v4.1.0.


回答1:


Use order query method for sorting the profile records based on url attribute of Profile

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

For ascending order you can specify asc instead of desc.

UPDATE

On second note, if you wish to retrieve profile records always sorted by url then update the Contact model as:

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

After this, contact.profiles would always result in sorted profiles based on url.



来源:https://stackoverflow.com/questions/25487098/order-an-activerecord-relation-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!