Forum: Ruby on Rails Managing acts_as_tree Model

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Hendie D. (Guest)
on 2005-11-23 09:40
(Received via mailing list)
I have a membership list based on the above. However, I allow for
prospective members to sign up with the reference (id) of a referer
(parent). So I am getting an id from ActiveView that I need to
validate and then slot the new member in as a child to the referer. I
managed to get the validation done to check that a member with the
supplied id does indeed exist, by adding the following to
validations.rb :

module ActiveRecord
  module Validations
    module ClassMethods
      def validates_id_exists(*attr_names)
        configuration = { :message => "is not valid" }
        configuration.update(attr_names.pop) if

        validates_each(attr_names, configuration) do |record, attr_name,
          record.errors.add(attr_name, configuration[:message]) unless
Member.find(:first, :conditions => ["id = ?", value.to_i])

Note the find, using find(id) would have raised an exception that I
don't want to deal with here. Then, in the model I just have:

validates_id_exists :associate_reference

Now for my question: I cannot really do the textbook
parent.children.create(<new member attrs>), since I need to allow
Rails to do its magic with validation of all the other fields on the
form (email, psw etc). So I opted for the following (attaching the
umbilical cord AFTER the save of the new record):

attr_accessor :associate_reference
def after_save
  if self.parent.nil? or self.associate_reference.to_i != # if new parent not same as old
    self.parent.children.delete(self) unless self.parent.nil?  #
remove me from old parent family
    parent = Member.find(self.associate_reference.to_i) # find new
    parent.children.push(self)  # add me to new parent family # should be ok to do this here

It works, but I have a feeling there must be a more elegant way of
doing this. Any words from the wise?
This topic is locked and can not be replied to.