订购ActiveRecord关系对象 [英] Order an ActiveRecord relation object

查看:93
本文介绍了订购ActiveRecord关系对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 contact 的ActiveRecord对象。它有一个名为 profiles 的关系。这些配置文件具有url属性。配置文件应按url的字母顺序排序。我试过 sort_by 以及 order ,但出现此错误:

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>

执行此操作的最佳方法是什么?我正在使用Rails v4.1.0。

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

推荐答案

使用订单查询方法,用于根据 url 属性对配置文件记录进行排序>个人资料

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

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

对于升序,您可以指定 asc desc

For ascending order you can specify asc instead of desc.

更新

第二点,如果您希望始终检索按 url 排序的个人档案记录 ,请更新 Contact 模型为:

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

此后, contact.profiles 始终生成基于 url 。

这篇关于订购ActiveRecord关系对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆