问题
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