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"?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With