Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.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 3 ActiveRecord在父级中排序子级_Ruby On Rails 3_Activerecord - Fatal编程技术网

Ruby on rails 3 ActiveRecord在父级中排序子级

Ruby on rails 3 ActiveRecord在父级中排序子级,ruby-on-rails-3,activerecord,Ruby On Rails 3,Activerecord,有没有办法通过ActiveRecord(Rails 3.2.13)对父对象的子对象进行预排序 所以如果你有这样的设置 class Parent < ActiveRecord::Base has_many :children [...] class Children < ActiveRecord::Base belongs_to :parent 类父级'd_o_b DESC') 这样,当我调用p.children时,我得到的是一个按出生排序的对象数组,而不是按其数据库ID排序的对

有没有办法通过ActiveRecord(Rails 3.2.13)对父对象的子对象进行预排序

所以如果你有这样的设置

class Parent < ActiveRecord::Base
has_many :children

[...]

class Children < ActiveRecord::Base
belongs_to :parent
类父级
大概是这样的:

p=Parent.where(:name=>'Diana')。包括(:children,:order=>'d_o_b DESC')

这样,当我调用
p.children
时,我得到的是一个按出生排序的对象数组,而不是按其数据库ID排序的对象数组


或者我只是需要在以后对数组进行排序吗?

在您的
父模型中,将
has\u many
更改为:

has_many :children, :order => 'd_o_b DESC'

然后,每当您访问父记录(例如,
@parent.children
)的
children
关联时,他们将按出生日期降序排列。

在您的
parent
模型中,将
has\u many
更改为:

has_many :children, :order => 'd_o_b DESC'

然后,每当您访问父记录(例如,
@parent.children
)的
children
关联时,他们将按照出生日期的降序排列。

:order
在Rails 4中的
has_many
中被弃用,更新的答案可用
:order
在Rails 4中的
has_many
中被弃用,有最新答案