Forum: Ruby on Rails How can I overwrite the parent.children.push(child) Method?

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.
Fc582698581884352e745d1d4c64699d?d=identicon&s=25 Joshua Muheim (josh)
on 2006-01-31 20:51
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. :-)

Greets
Josh
Ad7805c9fcc1f13efc6ed11251a6c4d2?d=identicon&s=25 Alex Young (Guest)
on 2006-02-01 13:49
(Received via mailing list)
Joshua Muheim 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. :-)

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.
Fc582698581884352e745d1d4c64699d?d=identicon&s=25 Joshua Muheim (josh)
on 2006-02-01 18:15
Thanks a lot. But I don't really get what to do now. ;-)

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?
This topic is locked and can not be replied to.