Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 订购ActiveRecord关系对象_Ruby On Rails_Activerecord - Fatal编程技术网

Ruby on rails 订购ActiveRecord关系对象

Ruby on rails 订购ActiveRecord关系对象,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有一个名为contact的ActiveRecord对象。它有一个名为profiles的关系。这些配置文件具有url属性。配置文件应按url按字母顺序排列。我尝试了sort\u by以及order,但出现了以下错误: contact.profiles.sort_by! { |profile| profile.url } undefined method `sort_by!' for #<Profile::ActiveRecord_Associations_CollectionProxy:0

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

contact.profiles.sort_by! { |profile| profile.url }
undefined method `sort_by!' for #<Profile::ActiveRecord_Associations_CollectionProxy:0x00000105d6d430>
contact.profiles.sort_by!{| profile | profile.url}
未定义的方法“排序依据!”为了#
最好的方法是什么?我使用的是Rails v4.1.0。

用于根据
profile的
url
属性对配置文件记录进行排序

contact.profiles.order(url: :desc) ## sort in descending order
对于升序,可以指定
asc
而不是
desc

更新

第二,如果您希望检索始终按
url
排序的配置文件记录,请将
联系人
模型更新为:

class Contact < ActiveRecord::Base
  # ...
  has_many :profiles, -> { order url: :desc } ## change order as per your requirement to asc / desc
  # ...
end
class联系人{订单url::desc}##根据您对asc/desc的要求更改订单
# ...
结束

在此之后,
contact.profiles
将始终根据
url

在替换
sort\u by使用
顺序形成我的示例,错误已消失,但配置文件未排序。更改数据是什么意思?您是否需要
contact.profiles
始终返回
profiles
url
排序的记录?请阅读答案中的更新部分。添加了一个额外的注释啊,是的,第二个解决方案解决了它。非常感谢!:)