Linus
Linus

Reputation: 4783

Order an ActiveRecord relation object

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.

Upvotes: 2

Views: 8625

Answers (1)

Kirti Thorat
Kirti Thorat

Reputation: 53048

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.

Upvotes: 8

Related Questions