Adding Add method to ActiveRecord array

Viewed 2455

I have the models Category and Products. If I use category.products << new_product the item gets added to the array and the record is saved to the database. I tried adding the following "add" method to the array class and while it does adds the new_product to the array, it does not save it to the database. Why is that?

class Array
  def add(item)
    self << item
  end
end

Update:

collection_proxy.rb has the following method:

def <<(*records)
  proxy_association.concat(records) && self
end
alias_method :push, :<<

So the following extension works:

class ActiveRecord::Relation
  def add(*records)
    proxy_association.concat(records) && self
  end
end

Solution:

Add an alias to the CollectionProxy:

class ActiveRecord::Associations::CollectionProxy
  alias_method :add, :<<
end
1 Answers
Related