【问题标题】:ActiveRecord sort children within parentActiveRecord 对父级中的子级进行排序
【发布时间】:2013-07-23 05:19:00
【问题描述】:

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

所以如果你有这样的设置

class Parent < ActiveRecord::Base
has_many :children

[...]

class Children < ActiveRecord::Base
belongs_to :parent

有些东西这样:

p = Parent.where(:name =&gt; 'Diana').includes(:children, :order =&gt; 'd_o_b DESC')

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

或者我只需要之后对我的数组进行排序?

【问题讨论】:

    标签: ruby-on-rails-3 activerecord


    【解决方案1】:

    在您的 Parent 模型中,将 has_many 更改为:

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

    然后,无论何时您访问父记录的 children 关联(例如@parent.children),它们都会按出生日期的降序排列。

    【讨论】:

    • :order 在 Rails 4 的 has_many 中被弃用,更新的答案可用 here
    猜你喜欢
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    相关资源
    最近更新 更多