Like ActsAsNestedSet, ActAsThreaded use the nested_set model : comparing to ActsAsTree, it’s slower to insert/delete/update (a whole set is updated) but the whole tree can be retrieved quickly from the database with a single query.
Great for creating threaded forums and other tree structures where read performance is a concern.
Ressources
The original link for Acts_as_threaded is now dead. More explanations can be found on this post (a zip too).
See also Plugins
Alternative
Bob Silva (who creates the plugin) proposed another way to do this without a plugin, using native Rails functionality . Same enhancements to acts_as_nested_set can be done adding 3 methods in your model :
Here’s the Code :
acts_as_nested_set :scope => :root
def before_create
# Update the child object with its parents attrs
unless self[:parent_id].to_i.zero?
self[:depth] = parent[:depth].to_i + 1
self[:root_id] = parent[:root_id].to_i
end
end
def after_create
# Update the parent root_id with its id
if self[:parent_id].to_i.zero?
self[:root_id] = self[:id]
self.save
else
parent.add_child self
end
end
def parent
@parent ||= self.class.find(self[:parent_id])
end
And here’s a migration :
class AddFieldsForActsAsNestedSet < ActiveRecord::Migration
def self.up
create_table :my_table_name, :force => true do |t|
t.column "root_id", :integer
t.column "parent_id", :integer
t.column "lft", :integer
t.column "rgt", :integer
t.column "depth", :integer
end
end
def self.down
drop_table :my_table_name, :root_id
end
end
See the post for possible update.
API documentation
Use ActsAsNestedSet, so :
Class methods
Instance methods
Questions