Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord Model Linked List

after intensive googling I will now state out a problem which seems to not occur often, but still is very basic. Linked Lists in Active Record. As far as I am now, 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 children of a parent:

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

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

like image 782
Daniel Richter Avatar asked Jul 04 '12 16:07

Daniel Richter


1 Answers

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

like image 181
Renan Avatar answered Sep 27 '22 21:09

Renan