Rails ActiveRecord model linked list

after an intensive search on Google Now I will focus on a problem that, it seems, does not often occur, but is still very simple. Linked lists in the active record. As far as I know, we need two associations in the model:

class Child < ActiveRecord::Base
  belongs_to :parent
  belongs_to :next, :class_name => 'Child', :foreign_key => 'next_id'
  belongs_to :previous, :class_name => 'Child', :foreign_key => 'previous_id'
end

So now we can get all the children of the parent:

children = Child.where("parent_id = ?", parent_id)

And now to the question: I want, of course, to get all the children from the database with one query, but I also want to go through the children in a related order, which means that the child with the previous attribute from nil will be the first, the next child will be the one which is bound by the first attribute firsts, and so on, until the next attribute is nil. Is it possible to do so, or do I need to request the first child, and then go from child to child without "prior training"?

+5
source share
2 answers

resort and ranked-model gems are other alternatives. The first uses an approach similar to linked lists. The second uses the position attribute.

+2

, Rails acts_as_list. belongs_to. , .

+1

All Articles