How can I overwrite the parent.children.push(child) Method?


#1

Hi all

I want to overwrite the push method (which is an alias of <<, the same
as concat) of collections, and there I want to test if :uniq is set to
true in the relationship. If so, the method should check if the passed
object is already related to the parent, or not (only then it will be
added).

But I just can’t find the original code of this method, so I could
overwrite it… Can anyone tell me? Thanks. :slight_smile:

Greets
Josh


#2

Joshua M. wrote:

Hi all

I want to overwrite the push method (which is an alias of <<, the same
as concat) of collections, and there I want to test if :uniq is set to
true in the relationship. If so, the method should check if the passed
object is already related to the parent, or not (only then it will be
added).

But I just can’t find the original code of this method, so I could
overwrite it… Can anyone tell me? Thanks. :slight_smile:

activerecord-1.13.2\lib\active_record\associations\association_collection.rb

has:

module ActiveRecord
module Associations
class AssociationCollection < AssociationProxy #:nodoc:

def <<(*records)
result = true
load_target
@owner.transaction do
flatten_deeper(records).each do |record|
raise_on_type_mismatch(record)
callback(:before_add, record)
result &&= insert_record(record) unless @owner.new_record?
@target << record
callback(:after_add, record)
end
end

     result and self
   end

   alias_method :push, :<<

But I’d think you’re better off not overriding that. Better to have a
wrapper method in the parent class.


#3

Thanks a lot. But I don’t really get what to do now. :wink:

module ActiveRecord
module Associations
class AssociationCollection < AssociationProxy #:nodoc:
def push_uniq(record)
# what to do here?
end
end
end
end

I’m quite confused with Rails’ internal codes… Where do I get the
already associated objects’ array from so I can check if the param
record is already incliuded in it?
Btw at the moment I only get a

ArgumentError: wrong number of arguments (1 for 0)

when I use Members.find(1).disc_jockeys.push_uniq(DiscJockey.find(1))

Why that?