Adding the Add Method to an ActiveRecord Array

I have Category models and products. If I use category.products << new_product, the element is added to the array and the record is saved in the database. I tried adding the following “add” class to the array class, and although it adds new_product to the array, it does not save it in the database. Why is this?

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

Decision:

Add an alias to CollectionProxy:

class ActiveRecord::Associations::CollectionProxy
  alias_method :add, :<<
end
+5
source share
1 answer

Edit: Manuel found a better solution

class ActiveRecord::Associations::CollectionProxy
  alias_method :add, :<<
end

Original solution:

This should help you get started. This is not perfect.

class ActiveRecord::Relation
  def add(attrs)
    create attrs
  end
end

, , , :

1.9.3p194 :006 > Artist.create(:first_name => "Kyle", :last_name => "G", :email => "foo@bar.com")
 => #<Artist id: 5, first_name: "Kyle", last_name: "G", nickname: nil, email: "foo@bar.com", created_at: "2012-08-16 04:08:30", updated_at: "2012-08-16 04:08:30", profile_image_id: nil, active: true, bio: nil> 
1.9.3p194 :007 > Artist.first.posts.count
 => 0 
1.9.3p194 :008 > Artist.first.posts.add :title => "Foo", :body => "Bar"
 => #<Post id: 12, title: "Foo", body: "Bar", artist_id: 5, created_at: "2012-08-16 04:08:48", updated_at: "2012-08-16 04:08:48"> 
1.9.3p194 :009 > Artist.first.posts.count
 => 1 
+2

All Articles