Joshua Muheim
2006-Jan-31 19:51 UTC
[Rails] How can I overwrite the parent.children.push(child) Method?
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 -- Posted via http://www.ruby-forum.com/.
Alex Young
2006-Feb-01 11:15 UTC
[Rails] How can I overwrite the parent.children.push(child) Method?
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. -- Alex
Joshua Muheim
2006-Feb-01 17:15 UTC
[Rails] Re: How can I overwrite the parent.children.push(child) Meth
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? -- Posted via http://www.ruby-forum.com/.