Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Add method to ActiveRecord array

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
like image 792
Manuel Avatar asked Nov 03 '22 18:11

Manuel


1 Answers

Edit: Manuel found a better solution

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

Original solution:

This should get you started. It's not perfect.

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

Rather than fire up a new rails project with your model names, I just used one I had for the following example:

1.9.3p194 :006 > Artist.create(:first_name => "Kyle", :last_name => "G", :email => "[email protected]")
 => #<Artist id: 5, first_name: "Kyle", last_name: "G", nickname: nil, email: "[email protected]", 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 
like image 70
Kyle Avatar answered Nov 08 '22 06:11

Kyle