针对Child的ActiveRecord查询,按祖父母排序

时间:2013-03-29 00:34:24

标签: ruby-on-rails activerecord

我看到很多关于在父元素上使用属性进行排序的例子,但是祖父母没有。如果有另外一篇文章详细说明了这一点,我找不到它,也许是因为我不知道这个词。所以,这是我的理论模型:

class GrandParent < ActiveRecord::Base
    has_many :parents
    has_many :children, through: :parents
end


class Parent < ActiveRecord::Base
    belongs_to :grand_parent
    has_many   :children
end


class Child < ActiveRecord::Base
    belongs_to :parent
end

所以,我正在尝试提供一份儿童名单,但我希望按照祖父母的方式排序。

我正在尝试像Child.joins(:grandparent).order('grandparent.name').all

这样无用的东西

但那不是为我做的。我尝试过其他一百种变种,但我不能说他们背后有太多的逻辑...... 有人对这个有什么好的想法吗?

2 个答案:

答案 0 :(得分:4)

你可以尝试

Child.joins(:parent => :grand_parent).order('grand_parents.name')

答案 1 :(得分:1)

如果您不关心速度,可以使用更明确的方法对这些易于理解的对象进行排序。特别是,

children.sort_by{|child| child.grand_parent.name}

它没有使用完整的SQL,如果你有很多children就不会很好,但有时为了易于实现而值得优化。

相关问题