Forum: Ruby on Rails Managing acts_as_tree Model

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Cf1ce45f343b1745f30ba70b3e208303?d=identicon&s=25 Hendie Dijkman (hendie)
on 2005-11-23 08: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 :

<rails-code>
module ActiveRecord
  module Validations
    module ClassMethods
      def validates_id_exists(*attr_names)
        configuration = { :message => "is not valid" }
        configuration.update(attr_names.pop) if
attr_names.last.is_a?(Hash)

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

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:

<rails_code>
validates_id_exists :associate_reference
</rails-code>

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):

<rails-code>
attr_accessor :associate_reference
def after_save
  if self.parent.nil? or self.associate_reference.to_i !=
self.parent.id # 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
    parent.children.push(self)  # add me to new parent family
    self.save # should be ok to do this here
  end
end
</rails-code>

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.