2

I'm seeing tons of examples of using attributes on a parent element for sorting, but nothing for grandparent. If there's another post out there detailing this, I couldn't find it, maybe because I don't know the word for it. So, here are my theoretical models:

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

So, I'm trying to present a list of children, but I want it sorted by grandparents.

I was trying useless things like Child.joins(:grandparent).order('grandparent.name').all

But that's just not doing it for me. I've attempted a hundred other variants, but I can't say they had much logic behind them... Anyone have any good thoughts on this one?

4

2 に答える 2

4

あなたは試すことができます

Child.joins(:parent => :grand_parent).order('grand_parents.name')
于 2013-03-29T17:25:29.940 に答える
1

速度を気にしない場合は、より明確な方法を使用して、これらのオブジェクトを簡単に並べ替えることができます。特に、

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

完全な SQL を使用していないためchildren、大量の .

于 2013-03-29T00:37:45.440 に答える