# This extension redefines the default behaviour of acts_as_tree function # to allow you to override the :dependent option for your trees # The default value defined in Rails is :destroy, but sometime you might want to use # a different cascade delete logic, or don't use cascade deleted at all. # # Usage: # 1. put this file into /lib/active_record_ext/ folder inside your rails application # 2. add the following string somewhere in the environment.rb file: # require 'active_record_ext/tree' # # This fix implements patch submitted to Rails development site, but not yet implemented # in main trunk of Rails. More info available at this link: # http://dev.rubyonrails.org/attachment/ticket/1924/allow_override_of_default_dependent_option_in_acts_as_tree.patch # # This extension should work without problems on Rails 1.2x, but of course I can not be held responsible # for any damage/loss/etc it might cause. # # http://macdiggs.com/index.php/2007/09/20/override-destroy-parameter-in-acts_as_tree-in-rails/ module ActiveRecord module Acts module Tree module ClassMethods def acts_as_tree(options = {}) configuration = { :foreign_key => "parent_id", :order => nil, :counter_cache => nil, :dependent => :destroy } configuration.update(options) if options.is_a?(Hash) belongs_to :parent, :class_name => name, :foreign_key => configuration[:foreign_key], :counter_cache => configuration[:counter_cache] has_many :children, :class_name => name, :foreign_key => configuration[:foreign_key], :order => configuration[:order], :dependent => configuration[:dependent] class_eval <<-EOV include ActiveRecord::Acts::Tree::InstanceMethods def self.roots find(:all, :conditions => "#{configuration[:foreign_key]} IS NULL", :order => #{configuration[:order].nil? ? "nil" : %Q{"#{configuration[:order]}"}}) end def self.root find(:first, :conditions => "#{configuration[:foreign_key]} IS NULL", :order => #{configuration[:order].nil? ? "nil" : %Q{"#{configuration[:order]}"}}) end EOV end end end end end